10

The interface Annotation specifies a method

Class<? extends Annotation> annotationType()

which has a zero-information1 javadoc. 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.

Community
  • 1
  • 1
maaartinus
  • 44,714
  • 32
  • 161
  • 320

2 Answers2

13

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

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.

Uri
  • 88,451
  • 51
  • 221
  • 321