Kim
Kim

Reputation: 5445

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

Upvotes: 5

Views: 4834

Answers (3)

Holger
Holger

Reputation: 298539

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.

Upvotes: 8

Ievgen Degtiarenko
Ievgen Degtiarenko

Reputation: 1

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

Upvotes: 0

Rafael Teles
Rafael Teles

Reputation: 2748

It looks like annotation is a proxy object

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

Upvotes: 0

Related Questions