Java参数化泛型类型列表创建不同类型的对象 [英] Java List of parameterized generic type creates different type of objects
问题描述
我有一个函数需要创建一个类型的对象列表,公共静态< T>列表与LT; T> readJsonFile(final String filePath){
List< T> objectsFromFile = NULL;
File file = new File(System.getProperty(catalina.base)+ filePath);
Gson gson = new Gson();
try(FileInputStream JSON = new FileInputStream(file)){
BufferedReader br = new BufferedReader(new InputStreamReader(JSON));
objectsFromFile = gson.fromJson(br,new TypeToken< List< T>>(){
} .getType());
} catch(Exception e){
e.printStackTrace();
}
返回objectsFromFile;
}
当我查看结果列表中的对象类型时,它们不是类型T(T将是我定义的不同类),但类型为 com.google.gson.internal.LinkedTreeMap 。
有谁知道为什么?我怎么能这样做,所以返回的列表是类型T?
这是因为泛型类型的令牌不工作到期删除。
您需要注入 TypeToken< List< T>>
作为参数,具体实例化。
public static< T>列表与LT; T> readJsonFile(
final String filePath,final TypeToken< List< T>> typeToken){
// ...
objectsFromFile = gson.fromJson(br,typeToken.getType());
// ...
}
然后将其命名为:
readJsonFile(/ path / to / file.json,new TypeToken< List< String>>(){}) ;
I have a function that needs to create a list of objects of a type that is passed in as a generic.
public static <T> List<T> readJsonFile(final String filePath) {
List<T> objectsFromFile=null;
File file = new File(System.getProperty("catalina.base") + filePath);
Gson gson = new Gson();
try (FileInputStream JSON = new FileInputStream(file)) {
BufferedReader br = new BufferedReader(new InputStreamReader(JSON));
objectsFromFile = gson.fromJson(br, new TypeToken<List<T>>() {
}.getType());
} catch (Exception e) {
e.printStackTrace();
}
return objectsFromFile;
}
When I look at the type of objects in the resulting list they are not of type T (T will be different classes that I defined) but of type com.google.gson.internal.LinkedTreeMap.
Does anyone know why? And how could I make it so the returned list is of type T?
It's because generic type tokens don't work due to erasure.
You need to inject the TypeToken<List<T>>
as a parameter, concretely instantiated.
public static <T> List<T> readJsonFile(
final String filePath, final TypeToken<List<T>> typeToken) {
// ...
objectsFromFile = gson.fromJson(br, typeToken.getType());
// ...
}
And then call this as:
readJsonFile("/path/to/file.json", new TypeToken<List<String>>() {});
这篇关于Java参数化泛型类型列表创建不同类型的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!