我正在尝试创建一个带有泛型的方法,将 JSON 列表解码为包含 POJO 的列表。下面的代码片段编译并运行,但在运行时我得到了我的 List<CustomPojo>
充满HashMap
实例,因为类型 T 不会传递到 TypeReference
构造函数然后回落到 HashMap
我猜。
public static <T> List<T> getList(String endpoint) throws IOException {
HttpGet request = new HttpGet(SERVER_ADDRESS + endpoint);
CloseableHttpResponse response = httpClient.execute(request);
try {
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == 200) {
return mapper.readValue(response.getEntity().getContent(), new TypeReference<List<T>>() { });
}
} finally {
response.close();
}
return null;
}
我走在正确的道路上还是使用泛型无法实现这一目标?
最佳答案
尝试使用类似的东西:
mapper.readValue(response.getEntity().getContent(),
mapper.getTypeFactory().contructCollectionType(List.class, cls);
其中 cls
是 Class<T>
它应该有效。
关于java - 将方法泛型类型传递给内部调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34919518/