简体   繁体   中英

Get fields of generic type object in Java

I have a class called "Person":

public Class Person {
    String name;
    String address;
}

A public method is used to return a Person object by using RestTemplate as below. My question is that how I print the name and the address of the Person object if I use generic type T for Person? I know I can do "instanceOf", but if "log" needs to handle many different types, then I will have to do "instanceOf" for each of them. Anyone has a better approach? Thanks.

public Person getPerson(SomeObject request) throws Exception {

    String url =......;
    return post(url, request, Pereson.class);
}

// This method can be used by response types other than Person
private <T> T post(String url, 
                   Object request, 
                   Class<T> responseType) throws Exception {

    T response = 
          restTemplate.postForObject(url, request, responseType);

    log(response, responseType);
    return response;
  }

private <T> void log(T response, 
                     Class<T> responseType) throws Exception {

    // how do I print the name and the address of the 
    // Person response object here?
 }

The easiest thing to do in this context is to delegate to the instance. Since you have no way to determine what that instance will be - it may be anything, really - the most effective way to log out critical information about the response would be to just invoke toString on response .

This means you need a suitable toString method attached to Person , which displays the name and address.

Anything else - dealing with instanceof or any kind of dodgy casting - is too risky and brittle when you need to introduce new classes which have to be logged.

There are a couple reasonable approached.

  • Have Person implement a Printable interface and declare T extends Person . (Using Object::toString makes this simpler, but may be the wrong thing to do.)
  • Add an adaptor (probably functional) interface, Printer (or even Printer<T> ), to stand in for Person . Write a set of overloaded static (or not) functions to wrap the likes of Person into Printer s (or even write inline as a lambda).

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