25.1 Basics of Annotations

Support for annotations is provided by the Annotation API, which is located in the java.lang.annotation package. The contents of this package are used to declare annotation types—as we shall see in this chapter.

As subpackages are not automatically imported, the types in the subpackage java.lang.annotation of the java.lang package must be explicitly imported in order to access them by their simple names—for example, by including a type-import-on-demand statement:

Click here to view code image

import java.lang.annotation.*;

Annotations are types that are a special kind of interfaces, analogous to enum types that are a special kind of class. An annotation must be declared before it can be used: An annotation type declaration must be defined, and when applied to a program element, an annotation designates a specific invocation of an annotation type. The java.lang.annotation.Annotation interface is a common interface implicitly extend by all annotation types, analogous to all classes implicitly extending the Object class. However, an annotation type declaration cannot explicitly extend the Annotation interface. Typically, an annotation type is declared as a top-level type, but can be nested like static member types. An annotation type declaration is compiled as any other Java type declaration, resulting in a class file containing its bytecode.

Click here to view code image

// Annotation type declaration with the name Tag.
@interface Tag {}              // Declaration always specified with
                               // at-sign (@) preceding the keyword interface.
__________________________________________________________________________
// Applying annotation @Tag which denotes the annotation type declaration Tag.
@Tag class Gizmo {            // Always applied with at-sign (@) preceding
                              // the annotation type name.
  @Tag void start() {}        // Another invocation of the annotation type Tag.
}

The code above shows the minimalistic declaration of an annotation type named Tag and its application to a class named Gizmo. What is important to note is that an annotation type declaration is specified with the at-sign (@) preceding the keyword interface, and when applied to a program element, the at-sign (@) precedes the annotation type name, and each application of the annotation to any program element denotes a different invocation of the annotation type. The rest of this chapter will elaborate on defining annotation type declarations and applying annotations to various program elements in the source code. The last section provides an introduction to annotation processing.

Leave a Reply

Your email address will not be published. Required fields are marked *