通过内省访问父类属性时出现非法访问异常

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"

我曾以为内省访问不会考虑修饰符,并且可以读取/写入甚至是私有成员。但事实并非如此。

我如何访问这些属性的值?

感谢您提前的帮助,

Raphael

2个回答

25

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

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

7
在调用field.get(this)之前,请尝试使用field.setAccessible(true)。默认情况下,修饰符会被识别,但可以关闭。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接