私は現在、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"
イントロスペクション アクセスは修飾子を気にせず、private メンバーでも読み書きできるようにしましたが、そうではないようです。
これらの属性の値にアクセスするにはどうすればよいですか?
よろしくお願いいたします。
ラファエル