简体   繁体   中英

Java List of parameterized generic type creates different type of objects

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM