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.
NOTE
A few folks recommend using Target and indicating all valid ElementTypes for documentation purposes. I think this is pretty silly, to be honest.
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.
package java.lang.annotation; 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 }
The default retention policy, for all annotations, is RetentionPolicy.CLASS. This retains annotations, but doesn't require the VM to read them 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:
@Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings {
NOTE
Don't forget to import java.lang. annotation. Retention and java.lang.annotation. Retention Policy.