我目前正在使用 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"
我认为自省访问不关心修饰符,甚至可以读/写私有成员。似乎事实并非如此。
如何访问这些属性的值?
在此先感谢您的帮助,
拉斐尔