[英]Generic method passing class as a parameter
如何对这种方法进行一致化? 我正在尝试在我的参数中接收一个类并从该类返回一个对象。
但是,Java表示返回的“any.class”int是未知的。
我是否在做泛型错误? 如何生成此方法以接收ResponseEntity和Class,然后从该类返回一个Object?
public static <T> T parseToJson(Class<T> any, ResponseEntity responseEntity) {
try {
return new ObjectMapper().readValue(responseEntity.getBody().toString(), any.class);
} catch (IOException e) {
logger.error("Error: " + e.getMessage());
}
}
还有一个疑问:如果我想返回一个对象数组,我曾经这样做过
return Arrays.asList(new ObjectMapper().readValue(responseEntity.getBody().toString(), ResponseListCameras[].class));
但我正在努力做到
return Arrays.asList(new ObjectMapper().readValue(responseEntity.getBody().toString(), any[]));
它似乎期待一种表达。 我能做什么?
any.class
更改为any
因为any
已经是Class<T>
实例。 try-catch
语句之后返回一些默认值,否则重新抛出异常。 否则,您将收到2个编译错误。
ResponseEntity
有一个类型参数。 在这里传递一个从getBody().toString()
提供的String
来反序列化json。
该方法看起来很奇怪,因为ResponseEntity
是一个泛型类, ResponseEntity.getBody()
返回泛型的实例。
所以你甚至不应该直接在这里使用杰克逊。
只要您正确使用ResponseEntity
就会对其进行输入。
例如 :
ResponseEntity<Foo> responseEntityFoo = template.getForEntity("/getAnUrl...", Foo.class);
Foo foo = responseEntityFoo.getBody();
所以你应该像这样反序列化JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.