我想创建一个通用方法来返回供应数据。这个想法是通过参数a Type.class
,当它使用 Gson
进行验证时,它将从 Type
返回一个集合或一个对象。
例如:
public class Client {
String id;
String name;
/* getters and setters */
}
public class Account {
String number;
String bank;
/* getters and setters */
}
public class Main {
public static void main(String[] args) {
List<Client> clients = Utils.getList(Client.class, "");
Account account = Utils.getSingle(Account.class, "number = '23145'");
}
}
public class Utils {
public static Class<? extends Collection> getList(Class<?> type, String query) {
//select and stuff, works fine and returns a Map<String, Object> called map, for example
Gson gson = new Gson();
JsonElement element = gson.fromJsonTree(map);
//Here's the problem. How to return a collection of type or a single type?
return gson.fromJson(element, type);
}
public static Class<?> getSingle(Class<?> type, String query) {
//select and stuff, works fine and returns a Map<String, Object> called map, for example
Gson gson = new Gson();
JsonElement element = gson.fromJsonTree(map);
//Here's the problem. How to return a collection of type or a single type?
return gson.fromJson(element, type);
}
}
如何从 Type
或列表中返回一个对象?
首先,您需要更改方法签名到通用类型:
public static <T> List<T> getList(Class<T> type, String query)
和
public static <T> T getSingle(Class<T> type, String query)
getSingle
方法应该开始工作,但是对于方法getList
,您需要更改实现:
创建
Type listType = new TypeToken<List<T>>() {}.getType();
return gson.fromJson(element, listType);
您可以从Javadoc中找到有关com.google.gson.Gson
的更多信息