[英]Generic method passing class as a parameter
How to generify this method? 如何对这种方法进行一致化? I'm trying to receive a class in my parameter and return a object from that class. 我正在尝试在我的参数中接收一个类并从该类返回一个对象。
However, Java says that "any.class" int the return is unknown. 但是,Java表示返回的“any.class”int是未知的。
Am I doing something wrong with generics? 我是否在做泛型错误? How can I generify this method to receive a ResponseEntity and a Class and then return a Object from that class? 如何生成此方法以接收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());
}
}
One more doubt: If I want to return a array of objects, I used to do 还有一个疑问:如果我想返回一个对象数组,我曾经这样做过
return Arrays.asList(new ObjectMapper().readValue(responseEntity.getBody().toString(), ResponseListCameras[].class));
but I'm trying to do 但我正在努力做到
return Arrays.asList(new ObjectMapper().readValue(responseEntity.getBody().toString(), any[]));
and it seems to expect an expression. 它似乎期待一种表达。 What can I do? 我能做什么?
any.class
to any
since any
is already a Class<T>
instance. 将any.class
更改为any
因为any
已经是Class<T>
实例。 try-catch
statement. 除非你想在try-catch
语句之后返回一些默认值,否则重新抛出异常。 Otherwise, you will get 2 compilation errors. 否则,您将收到2个编译错误。
ResponseEntity
has a type parameter. ResponseEntity
有一个类型参数。 Here you pass a String
provided from getBody().toString()
to deserialize the json. 在这里传递一个从getBody().toString()
提供的String
来反序列化json。
The approach looks weird because ResponseEntity
is a generic class and that ResponseEntity.getBody()
returns an instance of the generic. 该方法看起来很奇怪,因为ResponseEntity
是一个泛型类, ResponseEntity.getBody()
返回泛型的实例。
So you should not even use directly Jackson here. 所以你甚至不应该直接在这里使用杰克逊。
ResponseEntity
is typed as long as you use it correctly. 只要您正确使用ResponseEntity
就会对其进行输入。
For example : 例如 :
ResponseEntity<Foo> responseEntityFoo = template.getForEntity("/getAnUrl...", Foo.class);
Foo foo = responseEntityFoo.getBody();
So you should have the JSON deserialized just like that. 所以你应该像这样反序列化JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.