通用类型作为结果的参数

时间:2017-11-29 18:06:18

标签: java generics gson

我想创建一个返回反序列化数据的泛型方法。我们的想法是传递参数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或其列表中返回单个对象?

1 个答案:

答案 0 :(得分:2)

首先,您需要将方法签名更改为泛型类型:

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);

  3. 您可以从javaDoc

    找到有关com.google.gson.Gson的更多信息