通用类型作为结果参数



我想创建一个通用方法来返回供应数据。这个想法是通过参数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,您需要更改实现:

  1. 创建Type listType = new TypeToken<List<T>>() {}.getType();

  2. return gson.fromJson(element, listType);

您可以从Javadoc中找到有关com.google.gson.Gson的更多信息

最新更新