Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Annotation#annotationType() good for?

The interface Annotation specifies a method

Class<? extends Annotation> annotationType()

which has a zero-information1javadoc. I wonder what it is good for. All I could find is this question, but it's not actually needed there (as the two top answers below the accepted one shows).


It allows us to use

a.annotationType().equals(MyAnnotation.class)

but

a instanceof MyAnnotation

does the same job... except when a is an instance of a class implementing multiple annotations - but have anyone ever seen such a beast?

If a is an instance of class A implements MyAnnotation, YourAnnotation, then the two above tests are not equivalent, but the question is which one is better...

(*) It's like stating that getX() returns x.

like image 591
maaartinus Avatar asked Mar 29 '16 19:03

maaartinus


2 Answers

It's like getClass(), except due to the way annotations are implemented at runtime, getClass() frequently returns a nonsense type for annotation instances.

annotationType() returns "the right thing" -- the reflective type of the annotation, not some nonsense runtime type.

Compare Enum.getDeclaringClass(), which returns the "right thing" for an enum constant, whereas myEnumConstant.getClass() may return a synthetic subtype of the enum.

like image 136
Louis Wasserman Avatar answered Nov 15 '22 17:11

Louis Wasserman


One reason to use annotationType() is if your annotations are implemented using Proxy classes. Object.getClass() would return the proxy class whereas you may want the underlying "real" implementation class.

There are various examples of this, particularly when dependency injection or other heavyweight reflection is involved.

like image 39
Uri Avatar answered Nov 15 '22 19:11

Uri