[英]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.