How is it possible that an annotation can be an annotation for oneself?

I was looking at the JDK 7 documentation when I noticed an annotation called @Target in the java.lang.annotation . Title of this class

 @Documented @Retention(value=RUNTIME) @Target(value=ANNOTATION_TYPE) public @interface Target 

Now @Target used as an annotation for itself. How is this possible? @Target used in the title even before its announcement. I tried this with the annotations I wrote and it worked. Can anyone explain what is going on here?

+6
source share
1 answer

JLS specifically anticipates this, in section 9.6 Types of annotations :

If annotation a ( Β§9.7 ) by annotation type declaration corresponds to the annotation type T , and T has (meta-) annotation m , which corresponds to java.lang.annotation.Target , then m must either have an element whose value is java.lang.annotation.ElementType.ANNOTATION_TYPE , or an element whose value is java.lang.annotation.ElementType.TYPE , or a compile-time error occurs.

No other part of sections 9.6 or 9.7 says that it is forbidden to annotate the annotation declaration with reference to the annotated annotation.

+3
source

Source: https://habr.com/ru/post/949363/


All Articles