如何获得嵌套字段

时间:2014-05-07 09:41:12

标签: java reflection

我是反思的新手,我正试图获得一个嵌套的字段。总结我有以下几个类:

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)

我在哪里做错了?

2 个答案:

答案 0 :(得分:5)

目前的问题是没有字段的名称是" 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");

答案 1 :(得分: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);