JAVA - How to get annotations from Annotation?

2019-07-13 00:20发布

问题:

I want to get annotations from annotation, but the weird thing is I can't get single annotation from annotation instance. How do I solve this? I want to get annotations from this annotation instance.

public static void test(Annotation annotation) {
    System.out.println("ValidBoolean annotation len:" + ValidBoolean.class.getAnnotations().length);
    System.out.println(annotation.getClass().getName() + ":" + annotation.getClass().getAnnotations().length);
    if (annotation instanceof ValidBoolean) {
        ValidBoolean validBoolean = (ValidBoolean) annotation;
        System.out.println("[BOOLEAN]" + validBoolean.getClass().getName() + ":" + validBoolean.getClass().getAnnotations().length);
    }
}

print result is:

ValidBoolean annotation len:3
com.sun.proxy.$Proxy28:0
[BOOLEAN]com.sun.proxy.$Proxy28:0

回答1:

If I understand you correctly, you want to do

Annotation[] annotationAnnotations=annotation.annotationType().getAnnotations();

Generally, annotationType() works such that someClass.getAnnotation(someAnnotationClass).annotationType()==someAnnotationClass.

So annotation instanceof ValidBoolean also implies annotation.annotationType() == ValidBoolean.class, thus invoking .getAnnotations() on them will lead to the same annotations.



回答2:

It looks like annotation is a proxy object

 validBoolean.getClass().getSuperclass().getAnnotations().length


回答3:

I believe you can do

TopLevelAnnotation topLevelAnnotation = anything.get.getAnnotation(TopLevelAnnotation.class);
NestedAnnotation nestedAnnotation = topLevelAnnotation.annotationType().getAnnotation(NestedAnnotation.class);

Please check

/**
 * Returns the annotation type of this annotation.
 * @return the annotation type of this annotation
 */
java.lang.annotation.Annotation#annotationType()

in java.lang.annotation.Annotation