5

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

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like annotation is a proxy object

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

2 Comments

Still not working. Do you know how to get annotation from proxy? I'm not familiar with this.
I'm still not really understanding this Proxy mechanism. But I can get Annotation real class by annotation.annotationType() rather than annotation.getClass(), because annotation is just a interface so annotation.getClass() will only produce a Java Proxy object!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.