@Retention is a meta-annotation — it annotates other annotations. It controls how long an annotation stays around, governed by the RetentionPolicy enum.
publicenum RetentionPolicy { /** * Annotations are to be discarded by the compiler. */ SOURCE,
/** * Annotations are to be recorded in the class file by the compiler * but need not be retained by the VM at run time. This is the default * behavior. */ CLASS,
/** * Annotations are to be recorded in the class file by the compiler and * retained by the VM at run time, so they may be read reflectively. * * @see java.lang.reflect.AnnotatedElement */ RUNTIME }
Here’s the summary:
Policy
Description
Use Case
RetentionPolicy.SOURCE
Retained only in source files; discarded during compilation
Compile-time checks, e.g. @Override, @SuppressWarnings
RetentionPolicy.CLASS
Recorded in the .class file but discarded when the JVM loads it
Compile-time preprocessing, e.g. generating metadata (META-INF/services)
RetentionPolicy.RUNTIME
Recorded in the .class file and retained after JVM loads it
Runtime reflection, e.g. @Autowired, @Required
2. Seeing @Retention in the Bytecode
Define three annotations, one per retention policy: SourcePolicy, ClassPolicy, RuntimePolicy