2014-05-07 160 views
2

我是新的反射,我試圖得到一個嵌套字段。總結我有以下類別:如何獲得嵌套字段

public class Agreement{ 

    private Long id; 

    private String cdAgreement; 

    private Address address; 

    //Constructor getter and setter 

} 

public class Address{ 

    private Long id; 

    private String description; 

    //Constructor getter and setter 

} 

現在我想說明字段,然後我寫了這個代碼:

Agreement agreement = new Agreement(); 
Class c = agreement.getClass(); 
Field f = c.getDeclaredField("address.descritpion"); 

而不是作品,我得到以下異常:

java.lang.NoSuchFieldException: address.descritpion 
at java.lang.Class.getDeclaredField(Class.java:1948) 

我在哪裏做錯了?

回答

3

目前的問題是沒有字段的名稱爲「address.description」(它甚至不是字段的有效名稱)。

您必須首先獲取地址字段,訪問其類並從此處獲取嵌套字段。要做到這一點,使用getType()

Agreement agreement = new Agreement(); 
Class c = agreement.getClass();   // Agreement class 
Field f = c.getDeclaredField("address"); // address field 
Class<?> fieldClass = f.getType();  // class of address field (Address) 
Field nested = fieldClass.getDeclaredField("description"); // description field 

你也可以連接呼叫無局部變量:

Field nested = c.getDeclaredField("address").getType().getDeclaredField("description"); 
0

必須分解操作。

Agreement agreement = new Agreement(); 
Field fAddress = agreement.getClass().getDeclaredField("address"); 
Address address = (Address)fAddress.get(agreement); 
Field fDescription = address.getClass().getDeclaredField("description"); 
String description = (String)fDescription.get(address); 
+1

您不需要獲取字段的值,只需獲取其Class。而且,這可能會在調用'getClass()'時拋出NPE。 – Joffrey

+0

是的,你是對的。太倉促了。你的回答是對的。 – cadrian