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

Rap*_*vet 9 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

具有一些子属性的测试实现

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";

}
Run Code Online (Sandbox Code Playgroud)

测试本身:

TestClass test = new TestClass();
test.getChildren()
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

IllegalAccessException: Class AbstractClass can not access a member of class TestClass with modifiers "protected"
Run Code Online (Sandbox Code Playgroud)

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

如何访问这些属性的值?

在此先感谢您的帮助,

拉斐尔

Kir*_*oll 22

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

field.setAccessible(true);
result.add((ChildClass) field.get(this));
Run Code Online (Sandbox Code Playgroud)


Tho*_*zer 7

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