简体   繁体   English

将类作为参数传递的通用方法

[英]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? 我能做什么?

  1. Change any.class to any since any is already a Class<T> instance. any.class更改为any因为any已经是Class<T>实例。
  2. Rethrow the exception unless you want to return something default after the try-catch statement. 除非你想在try-catch语句之后返回一些默认值,否则重新抛出异常。

Otherwise, you will get 2 compilation errors. 否则,您将收到2个编译错误。

  1. Don't use raw types. 不要使用原始类型。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM