Reputation: 2037
I was browsing through the documentation of JDK 7 when I noticed an annotation called @Target
in package java.lang.annotation
. The header of that class is
@Documented
@Retention(value=RUNTIME)
@Target(value=ANNOTATION_TYPE)
public @interface Target
Now, @Target
is used as an annotation to itself. How is this possible? @Target
is used in the header even before it is declared. I tried this with annotations I had written, and it worked as well. Can anyone explain what's happening here?
Upvotes: 7
Views: 580
Reputation: 20919
The JLS specifically anticipates this, in section 9.6 Annotation Types:
If an annotation
a
(§9.7) on an annotation type declaration corresponds to an annotation typeT
, andT
has a (meta-)annotationm
that corresponds tojava.lang.annotation.Target
, thenm
must have either an element whose value isjava.lang.annotation.ElementType.ANNOTATION_TYPE
, or an element whose value isjava.lang.annotation.ElementType.TYPE
, or a compile-time error occurs.
No other part of section 9.6 or 9.7 says anything about it being illegal for an annotation declaration to be annotated with a reference to the annotation being declared.
Upvotes: 3