所以我有一个调用API的服务,它返回一个将映射到类的JsonParser对象。它只需更改即可完美地重复相同的代码:
new TypeReference<ActualClass>() {}
例如:
new TypeReference<List<Map<String, Model>>>() {}
我正在尝试通过创建一种通用的方法来创建更清晰,更好的代码。我尝试使用通用方法,但这是不可能的,或者我不能这样做。
public <T> T get(Class<T> clazz, Connection connection, ObjectMapper mapper, String errorMessage) { ... }
我无法通过以下课程:
get(List<Map<String, Model>>.class <- this will fail.
所以我尝试使用泛型类:
private static class Executor<T> {
private ObjectMapper mapper;
private Connection connection;
private String errorMessage;
public Executor(Connection connection, ObjectMapper mapper, String errorMeesage) {
this.mapper = mapper;
this.connection = connection;
this.errorMessage = errorMeesage;
}
public T get(final String url) {
T result = null;
JsonParser dataReceived = null;
try {
dataReceived = connection.getData(url);
if (dataReceived != null) {
result = mapper.readValue(dataReceived, new TypeReference<T>() {});
}
} catch (IOException e) {
logger.error(errorMessage, e);
throw new Exception();
}
return result;
}
}
它编译,但我收到此错误:.lang.ClassCastException:java.util.LinkedHashMap无法转换为...
我读了一点,我认为这必须是Java的某种限制。帮助将不胜感激:),谢谢。