简体   繁体   English

获取Java中通用类型对象的字段

[英]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. 公共方法用于通过使用RestTemplate来返回Person对象,如下所示。 My question is that how I print the name and the address of the Person object if I use generic type T for Person? 我的问题是,如果我对Person使用通用类型T,如何打印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. 我知道我可以执行“ instanceOf”,但是如果“ log”需要处理许多不同的类型,那么我将必须为每个类型执行“ instanceOf”。 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 . 既然你没有办法确定这个实例将是什么 -它可以是任何东西,真的-注销有关工作的关键信息的最有效的方法是只调用toStringresponse

This means you need a suitable toString method attached to Person , which displays the name and address. 这意味着您需要一个附加到Person的合适的toString方法,该方法显示名称和地址。

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. 当您需要引入必须记录的新类时, 其他任何事情 -处理instanceof或任何类型的躲猫猫-都太冒险和脆弱。

There are a couple reasonable approached. 有一些合理的方法。

  • Have Person implement a Printable interface and declare T extends Person . Person实现一个Printable接口并声明T extends Person (Using Object::toString makes this simpler, but may be the wrong thing to do.) (使用Object::toString可以简化此过程,但是这样做可能是错误的。)
  • Add an adaptor (probably functional) interface, Printer (or even Printer<T> ), to stand in for Person . 添加一个适配器(可能是功能性的)接口, Printer (甚至是Printer<T> )来代替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). 编写一组重载的静态(或非静态)函数,以将Person包装到Printer (甚至内联为lambda编写)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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