0

假设我有两个以下课程

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

This is a possible way which doesn't use objects in children. It inspects generic type of children and scans this class to find an annotation.

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

See this guide for more information about annotations.

于 2012-12-26T01:05:55.213 回答