6.8 Setting the Retention of an Annotation Type
The Retention meta-annotation annotation defines how the Java compiler
treats annotations. Annotations
can be tossed out of a compiled
class file by the compiler, or kept in the class file. Additionally, the Java
virtual machine can ignore annotations (when they are retained in the
class file), or read those annotations at the time a class is first loaded. All
of these options are specified by Retention.NOTEA few folks
recommend using
Target and
indicating all valid
ElementTypes for
documentation
purposes. I think
this is pretty silly,
to be honest.
6.8.1 How do I do that?
Like Target, you specify the retention of an annotation type just before
the annotation definition (the public @interface line). Also, like Target,
the argument to Retention must be a value from an enum support classin this case, java.lang.annotation.RetentionPolicy. This enum is
shown in Example 6-11.
Example 6-11. The RetentionPolicy enum
package java.lang.annotation;The default retention policy, for all annotations, is RetentionPolicy.CLASS. This retains annotations, but doesn't require the VM to read them
public enum RetentionPolicy {
SOURCE, // Annotation is discarded by the compiler
CLASS, // Annotation is stored in the class file, but ignored by the VM
RUNTIME // Annotation is stored in the class file and read by the VM
}
when classes are loaded.A good example of using Retention occurs in the SuppressWarnings
annotation. As that annotation type is purely used for compilation (ensuring
warnings of the specified type are suppressed), it does not need to be
retained in a class's bytecode:
NOTEDon't forget to
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
import java.lang.
annotation.
Retention and
java.lang.annotation.
Retention
Policy.