Reputation: 625
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?
Upvotes: 0
Views: 213
Reputation: 140484
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>>() {});
Upvotes: 4