11

我目前正在使用 Java 1.5 中的自省和注释。有一个父抽象类AbstractClass继承的类可以具有使用自定义@ChildAttribute注释注释的属性(类型为ChildClass)。

我想编写一个通用方法来列出实例的所有@ChildAttribute属性。

到目前为止,这是我的代码。

父类:

public abstract class AbstractClass {

    /** List child attributes (via introspection) */
    public final Collection<ChildrenClass> getChildren() {

        // Init result
        ArrayList<ChildrenClass> result = new ArrayList<ChildrenClass>();

        // Loop on fields of current instance
        for (Field field : this.getClass().getDeclaredFields()) {

            // Is it annotated with @ChildAttribute ?
            if (field.getAnnotation(ChildAttribute.class) != null) {
                result.add((ChildClass) field.get(this));
            }

        } // End of loop on fields

        return result;
    }
}

一个测试实现,带有一些子属性

public class TestClass extends AbstractClass {

    @ChildAttribute protected ChildClass child1 = new ChildClass();
    @ChildAttribute protected ChildClass child2 = new ChildClass();
    @ChildAttribute protected ChildClass child3 = new ChildClass();

    protected String another_attribute = "foo";

}

测试本身:

TestClass test = new TestClass();
test.getChildren()

我收到以下错误:

IllegalAccessException: Class AbstractClass can not access a member of class TestClass with modifiers "protected"

我认为自省访问不关心修饰符,甚至可以读/写私有成员。似乎事实并非如此。

如何访问这些属性的值?

在此先感谢您的帮助,

拉斐尔

4

2 回答 2

24

在获取值之前添加 field.setAccessible(true) :

field.setAccessible(true);
result.add((ChildClass) field.get(this));
于 2010-08-13T13:04:35.760 回答
7

field.setAccessible(true)打电话前先试试field.get(this)。默认情况下,修饰符被尊重,但可以关闭。

于 2010-08-13T13:04:40.267 回答