尝试通过内省从父类访问attibrute时出现非法访问异常

时间:2010-08-13 13:00:05

标签: java introspection java-5

我目前正在玩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"

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

如何访问这些属性的值?

先谢谢你的帮助,

Raphael

2 个答案:

答案 0 :(得分:22)

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

field.setAccessible(true);
result.add((ChildClass) field.get(this));

答案 1 :(得分:7)

在致电field.setAccessible(true)之前尝试field.get(this)。默认情况下,修饰符可以使用,但可以关闭。