Java Reference
In-Depth Information
This declares an annotation called MyAnno . Notice the @ that precedes the keyword in-
terface . This tells the compiler that an annotation type is being declared. Next, notice
the two members str( ) and val( ) . All annotations consist solely of method declarations.
However, you don't provide bodies for these methods. Instead, Java implements these
methods. Moreover, the methods act much like fields.
All annotation types automatically extend the Annotation interface. Thus, Annotation
is a super-interface of all annotations. It is declared within the java.lang.annotation pack-
age.
Originally, annotations were used to annotate only declarations. In this usage, any type
of declaration can have an annotation associated with it. For example, classes, methods,
fields, parameters, and enum constants can be annotated. Even an annotation can be annot-
ated. In such cases, the annotation precedes the rest of the declaration. Beginning with JDK
8, you can also annotate a type use , such as a cast or a method return type.
When you apply an annotation, you give values to its members. For example, here is an
example of MyAnno being applied to a method:
This annotation is linked with the method myMeth( ) . Look closely at the annotation syn-
tax. The name of the annotation, preceded by an @, is followed by a parenthesized list of
member initializations. To give a member a value, that member's name is assigned a value.
Therefore, in the example, the string "Annotation Example" is assigned to the str member
of MyAnno . Notice that no parentheses follow str in this assignment. When an annotation
member is given a value, only its name is used. Thus, annotation members look like fields
in this context.
Annotations that don't have parameters are called marker annotations . These are speci-
fied without passing any arguments and without using parentheses. Their sole purpose is to
mark an item with some attribute.
Java defines many built-in annotations. Most are specialized, but nine are general pur-
pose. Four are imported from java.lang.annotation : @ Retention , @ Documented , @ Tar-
Search WWH ::




Custom Search