gpt4 book ai didi

java - 通用类型作为结果的参数

转载 作者:行者123 更新时间:2023-12-02 02:27:45 25 4
gpt4 key购买 nike

我想创建一个通用方法来返回反序列化数据。这个想法是传递参数 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);

您可以找到有关com.google.gson.Gson的更多信息来自javaDoc

关于java - 通用类型作为结果的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47559079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com