8.5 Standard Annotations
Java SE defines a number of annotation interfaces in the java.lang, java.lang.annotation, and javax.annotation packages. Four of them are meta-annotations that describe the behavior of annotation interfaces. The others are regular annotations that you can use to annotate items in your source code. Table 8.2 shows these annotations. We’ll discuss them in detail in the following two sections.
Table 8.2 The Standard Annotations
Annotation Interface |
Applicable To |
Purpose |
Deprecated |
All |
Marks item as deprecated. |
SuppressWarnings |
All but packages |
Suppresses warnings of the given type. |
SafeVarargs |
Methods and |
Asserts that the varargs parameter is safe |
Override |
Methods |
Checks that this method overrides a |
FunctionalInterface |
Interfaces |
Marks an interface as functional (with a |
PostConstruct |
Methods |
The marked method should be invoked |
Resource |
Classes, interfaces, |
On a class or interface, marks it as a |
Resources |
Classes, interfaces |
Specifies an array of resources. |
Generated |
All |
Marks an item as source code that has |
Target |
Annotations |
Specifies the items to which this |
Retention |
Annotations |
Specifies how long this annotation is |
Documented |
Annotations |
Specifies that this annotation should be |
Inherited |
Annotations |
Specifies that this annotation, when |
Repeatable |
Annotations |
Specifies that this annotation can be |
8.5.1 Annotations for Compilation
The @Deprecated annotation can be attached to any items whose use is no longer encouraged. The compiler will warn when you use a deprecated item. This annotation has the same role as the @deprecated Javadoc tag.
The @SuppressWarnings annotation tells the compiler to suppress warnings of a particular type, for example,
@SuppressWarnings("unchecked")
The @Override annotation applies only to methods. The compiler checks that a method with this annotation really overrides a method from the superclass. For example, if you declare
public MyClass { @Override public boolean equals(MyClass other); . . . }
then the compiler will report an error. After all, the equals method does not override the equals method of the Object class because that method has a parameter of type Object, not MyClass.
The @Generated annotation is intended for use by code generator tools. Any generated source code can be annotated to differentiate it from programmer-provided code. For example, a code editor can hide the generated code, or a code generator can remove older versions of generated code. Each annotation must contain a unique identifier for the code generator. A date string (in ISO 8601 format) and a comment string are optional. For example,
@Generated("com.horstmann.beanproperty", "2008-01-04T12:08:56.235-0700");
8.5.2 Annotations for Managing Resources
The @PostConstruct and @PreDestroy annotations are used in environments that control the lifecycle of objects, such as web containers and application servers. Methods tagged with these annotations should be invoked immediately after an object has been constructed or immediately before it is being removed.
The @Resource annotation is intended for resource injection. For example, consider a web application that accesses a database. Of course, the database access information should not be hardwired into the web application. Instead, the web container has some user interface for setting connection parameters and a JNDI name for a data source. In the web application, you can reference the data source like this:
@Resource(name="jdbc/mydb") private DataSource source;
When an object containing this field is constructed, the container “injects” a reference to the data source.
8.5.3 Meta-Annotations
The @Target meta-annotation is applied to an annotation, restricting the items to which the annotation applies. For example,
@Target({ElementType.TYPE, ElementType.METHOD}) public @interface BugReport
Table 8.3 shows all possible values. They belong to the enumerated type ElementType. You can specify any number of element types, enclosed in braces.
Table 8.3 Element Types for the @Target Annotation
Element Type |
Annotation Applies To |
ANNOTATION_TYPE |
Annotation type declarations |
PACKAGE |
Packages |
TYPE |
Classes (including enum) and interfaces (including annotation types) |
METHOD |
Methods |
CONSTRUCTOR |
Constructors |
FIELD |
Fields (including enum constants) |
PARAMETER |
Method or constructor parameters |
LOCAL_VARIABLE |
Local variables |
TYPE_PARAMETER |
Type parameters |
TYPE_USE |
Uses of a type |
An annotation without an @Target restriction can be applied to any item. The compiler checks that you apply an annotation only to a permitted item. For example, if you apply @BugReport to a field, a compile-time error results.
The @Retention meta-annotation specifies how long an annotation is retained. You can specify at most one of the values in Table 8.4. The default is RetentionPolicy.CLASS.
Table 8.4 Retention Policies for the @Retention Annotation
Retention Policy |
Description |
SOURCE |
Annotations are not included in class files. |
CLASS |
Annotations are included in class files, but the virtual machine |
RUNTIME |
Annotations are included in class files and loaded by the virtual |
In Listing 8.11 on p. 461, the @ActionListenerFor annotation was declared with RetentionPolicy.RUNTIME because we used reflection to process annotations. In the following two sections, you will see examples of processing annotations at the source and class file levels.
The @Documented meta-annotation gives a hint to documentation tools such as Javadoc. Documented annotations should be treated just like other modifiers, such as protected or static, for documentation purposes. The use of other annotations is not
included in the documentation. For example, suppose we declare @ActionListenerFor as a documented annotation:
@Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ActionListenerFor
Now the documentation of each annotated method contains the annotation, as shown in Figure 8.2.
Figure 8.2 Documented annotations
If an annotation is transient (such as @BugReport), you should probably not document its use.
The @Inherited meta-annotation applies only to annotations for classes. When a class has an inherited annotation, then all of its subclasses automatically have the same annotation. This makes it easy to create annotations that work as marker interfaces, such as Serializable.
In fact, an annotation @Serializable would be more appropriate than the Serializable marker interface with no methods. A class is serializable because there is runtime support for reading and writing its fields, not because of any principles of object-oriented design. An annotation describes this fact better than does interface inheritance. Of course, the Serializable interface was created in JDK 1.1, long before annotations existed.
Suppose you define an inherited annotation @Persistent to indicate that objects of a class can be saved in a database. Then the subclasses of persistent classes are automatically annotated as persistent.
@Inherited @interface Persistent { } @Persistent class Employee { . . . } class Manager extends Employee { . . . } // also @Persistent
When the persistence mechanism searches for objects to store in the database, it will detect both Employee and Manager objects.
As of Java SE 8, it is legal to apply the same annotation type multiple times to an item. For backward compatibility, the implementor of a repeatable annotation needs to provide a container annotation that holds the repeated annotations in an array.
Here is how to define the @TestCase annotation and its container:
@Repeatable(TestCases.class) @interface TestCase { String params(); String expected(); } @interface TestCases { TestCase[] value(); }
Whenever the user supplies two or more @TestCase annotations, they are automatically wrapped into a @TestCases annotation.