简体   繁体   中英

JAVA - How to get annotations from Annotation?

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

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.

看起来注解是一个代理对象

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM