Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible that an annotation can be an annotation to itself?

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?

like image 518
JavaNewbie_M107 Avatar asked Jul 13 '13 11:07

JavaNewbie_M107


People also ask

What is an annotation what can be annotated and how?

Annotations are used to provide supplemental information about a program. Annotations start with '@'. Annotations do not change the action of a compiled program. Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.

What is annotation and how it works?

Annotation can be: A systematic summary of the text that you create within the document. A key tool for close reading that helps you uncover patterns, notice important words, and identify main points. An active learning strategy that improves comprehension and retention of information.

What is the purpose of the annotations?

Annotating is any action that deliberately interacts with a text to enhance the reader's understanding of, recall of, and reaction to the text. Sometimes called "close reading," annotating usually involves highlighting or underlining key pieces of text and making notes in the margins of the text.

Can we create our own annotations in Java?

To create your own Java Annotation you must use @interface Annotation_name, this will create a new Java Annotation for you. The @interface will describe the new annotation type declaration. After giving a name to your Annotation, you will need to create a block of statements inside which you may declare some variables.


1 Answers

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 type T, and T has a (meta-)annotation m that corresponds to java.lang.annotation.Target, then m must have either 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 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.

like image 132
Matt McHenry Avatar answered Oct 11 '22 13:10

Matt McHenry