如何返回与返回类型相同的classType(第二个参数)?
public Object getJsonPojo(String fileName, Class classType) {
try {
return objectMapper.readValue(new File(classLoader.getResource(fileName).getFile()), classType);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
现在我只能像下面这样打电话
A obj = (A) getJsonPojo("filePath", A.class);
例如,我想要类似以下内容(不强制转换):
A obj = getJsonPojo("filePath", A.class);
答案 0 :(得分:1)
在方法级别和显式强制转换上使用通用参数。
public <T> T getJsonPojo(String fileName, Class<T> classType) {
try {
File file = new File(classLoader.getResource(fileName).getFile());
return (T) objectMapper.readValue(file, classType);
} catch (IOException e) {
e.printStackTrace();
}
}
或者,通用类型<T>
可以出现在类级别。
无论如何,请勿使用原始Class
,而应指定通用类型Class<T>
。