Java List of parameterized generic type creates different type of objects

折月煮酒 提交于 2019-12-12 05:44:25

问题


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?


回答1:


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>>() {});


来源:https://stackoverflow.com/questions/36840799/java-list-of-parameterized-generic-type-creates-different-type-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!