0

以下の2つのクラスがあるとします

class Parent extends MyBase {
    @Annot(key="some.key", ref=Child.class)
    public List<Child> children = new List<Child>();
}

class Child extends MyBase {
    @Annot(key="another.key")
    public String id;
}

今私が持っていると言う

  • クラスParentオブジェクト =>parentおよび
  • リストに3 つChildのクラス オブジェクトが含まれていchildrenます。

parent.children.get(0).idアクセスできるということです。ここで、属性のキー シーケンスを形成する必要がありますid。これは、注釈Key Sequenceのすべてのkey値を連結した文字列です。@Annotたとえば、この場合、キー シーケンスは次のようになります。some.key/another.key

Javaリフレクションを介してそれを行う方法はありますか?

4

1 に答える 1

0

これは、でオブジェクトを使用しない可能性のある方法ですchildren。ジェネリック型の子を検査し、このクラスをスキャンしてアノテーションを見つけます。

    Field childrenField = Parent.class.getField("children");
    Annotation[] annotations = childrenField.getDeclaredAnnotations();

    String key = null;
    for (Annotation annotation : annotations) {
        if (annotation instanceof Annot) {
            Annot a = (Annot) annotation;
            key = a.key();
            break;
        }
    }

    ParameterizedType type = (ParameterizedType) childrenField.getGenericType();
    Class<?> c = (Class<?>) type.getActualTypeArguments()[0];
    annotations = c.getDeclaredField("id").getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation instanceof Annot) {
            Annot a = (Annot) annotation;
            key += "/" + a.key();
            break;
        }
    }

    System.out.println(key);

注釈の詳細については、このガイドを参照してください。

于 2012-12-26T01:05:55.213 に答える