In general, you should restrict your use of the type wrappers to only those cases in which
an object representation of a primitive type is required. Autoboxing/unboxing was not added
to Java as a "back door" way of eliminating the primitive types.
Annotations (Metadata)
Beginning with JDK 5, a new facility was added to Java that enables you to embed
supplemental information into a source file. This information, called an annotation, does not
change the actions of a program. Thus, an annotation leaves the semantics of a program
unchanged. However, this information can be used by various tools during both development
and deployment. For example, an annotation might be processed by a source-code generator.
The term metadata is also used to refer to this feature, but the term annotation is the most
descriptive and more commonly used.
Annotation Basics
An annotation is created through a mechanism based on the interface. Let's begin with an
example. Here is the declaration for an annotation called MyAnno:
// A simple annotation type.
@interface MyAnno {
String str();
int val();
First, notice the @ that precedes the keyword interface. 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, as you will see.
An annotation cannot include an extends clause. However, 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 package. It overrides hashCode( ),
equals( ), and toString( ), which are defined by Object. It also specifies annotationType( ),
which returns a Class object that represents the invoking annotation.
Once you have declared an annotation, you can use it to annotate a declaration. 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 annotated.
In all cases, the annotation precedes the rest of the declaration.
When you apply an annotation, you give values to its members. For example, here is an
example of MyAnno being applied to a method:
// Annotate a method.
@MyAnno(str = "Annotation Example", val = 100)
public static void myMeth() { // ...
This annotation is linked with the method myMeth( ). Look closely at the annotation syntax.
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.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks