我正在写一个帮助函数。getList将从某个地方获得序列化的数据,并对其进行反序列化。
getList总是返回一个列表。用户将指定元素的类型。预期用法如下:
List<Asset> l1 = getList("Asset"); //warning Unchecked assignment is fine
List<Store> l2 = getList("Store");
//or
List<Asset> l1 = getList(Asset.class);
List<Store> l2 = getList(Store.class);
//or
List<Asset> l1 = getList<Asset>();
List<Store> l2 = getList<Store>();我该如何修复下面的实现?它不会编译,因为className是一个变量,而List<>需要一个类。
public static List getList(String className)
{
Genson genson = new Genson();
String data = ...
List l= genson.deserialize(data, List<className>);
~~~~~~~~~~~~~~~
return l;
}发布于 2021-08-28 11:30:38
在http://genson.io/GettingStarted上有一个geson的入门指南。下面是泛型类型的示例:
List<Person> persons = genson.deserialize(json, new GenericType<List<Person>>(){});如果要将列表元素的类型传递给该方法,可以引入一个type参数:
public static <T> List<T> getList(String json, Class<T> clazz) {
Genson genson = new Genson();
List<T> list = genson.deserialize(json, new GenericType<List<T>>(){});
return list;
}使用该方法的示例将如下所示:
public static void main(String[] args) {
List<String> stringList = getList("[ \"element1\", \"element2\" ]", String.class);
System.out.println(stringList);
List<Integer> integerList = getList("[ 1, 2, 3 ]", Integer.class);
System.out.println(integerList);
}这将产生以下输出:
[element1, element2]
[1, 2, 3]https://stackoverflow.com/questions/68953603
复制相似问题