gpt4 book ai didi

java - 无法构造泛型类型参数,该怎么办?

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:02 25 4
gpt4 key购买 nike

Possible Duplicate:
Create instance of generic type in Java?

在尝试编写以下内容后,我才发现 Java 不允许您构造泛型类型参数的新实例:

public static <C extends JSONSerializable> List<C> JSONtoList(JSONArray data) {
List<C> list = new ArrayList<C>();
for (int i = 0; i < data.length(); i++){
list.add(new C(data.get(i)));
}
return list;
}

这不能编译,但我认为我想要做的事情很明显。我该怎么做?

最佳答案

如果您使用 GSON,这实际上非常简单:

public static <C extends JSONSerializable> List<C> jsonToList(JsonArray data, Class<C> type) {
Gson gson = new Gson();
List<C> list = new ArrayList<C>();
for (JsonElement e : data)
list.add(gson.fromJson(e, type));
return list;
}

否则,您将需要使用反射或ClassnewInstance方法。

关于java - 无法构造泛型类型参数,该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9918285/

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