[英]Get fields of generic type object in Java
我有一堂课叫做“人”:
public Class Person {
String name;
String address;
}
公共方法用于通过使用RestTemplate来返回Person对象,如下所示。 我的问题是,如果我对Person使用通用类型T,如何打印Person对象的名称和地址? 我知道我可以执行“ instanceOf”,但是如果“ log”需要处理许多不同的类型,那么我将必须为每个类型执行“ instanceOf”。 有人有更好的方法吗? 谢谢。
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?
}
在这种情况下,最简单的事情就是委托给实例。 既然你没有办法确定这个实例将是什么 -它可以是任何东西,真的-注销有关工作的关键信息的最有效的方法是只调用toString
的response
。
这意味着您需要一个附加到Person
的合适的toString
方法,该方法显示名称和地址。
当您需要引入必须记录的新类时, 其他任何事情 -处理instanceof
或任何类型的躲猫猫-都太冒险和脆弱。
有一些合理的方法。
Person
实现一个Printable
接口并声明T extends Person
。 (使用Object::toString
可以简化此过程,但是这样做可能是错误的。) Printer
(甚至是Printer<T>
)来代替Person
。 编写一组重载的静态(或非静态)函数,以将Person
包装到Printer
(甚至内联为lambda编写)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.