简体   繁体   中英

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.

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?

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.
  2. Rethrow the exception unless you want to return something default after the try-catch statement.

Otherwise, you will get 2 compilation errors.

  1. Don't use raw types. ResponseEntity has a type parameter.

Here you pass a String provided from getBody().toString() to deserialize the json.
The approach looks weird because ResponseEntity is a generic class and that ResponseEntity.getBody() returns an instance of the generic.
So you should not even use directly Jackson here.

ResponseEntity is typed as long as you use it correctly.

For example :

ResponseEntity<Foo> responseEntityFoo = template.getForEntity("/getAnUrl...", Foo.class);
Foo foo = responseEntityFoo.getBody();   

So you should have the JSON deserialized just like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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