What is Retention Policy in Java Annotation Explained
RetentionPolicy defines how long an annotation is kept: only in source code, in the compiled class files, or available at runtime. It controls whether the annotation is discarded by the compiler or retained for reflection during program execution.How It Works
Think of a retention policy like a note you write on a document. Some notes you only need while writing (source), some you want to keep with the document but not show when reading (class), and some you want to keep visible even when the document is being used (runtime).
In Java, annotations can have different retention policies that tell the compiler and JVM how long to keep the annotation information. The three main types are SOURCE, CLASS, and RUNTIME. SOURCE means the annotation is only in the source code and removed during compilation. CLASS means the annotation is stored in the compiled class file but not available at runtime. RUNTIME means the annotation is kept in the class file and can be read during program execution using reflection.
This mechanism helps Java decide if annotations are just for developers or also for the program to use while running.
Example
This example shows how to define an annotation with a retention policy and how it affects availability at runtime.
import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { String value(); } @MyAnnotation("Hello") public class Test { public static void main(String[] args) { MyAnnotation annotation = Test.class.getAnnotation(MyAnnotation.class); if (annotation != null) { System.out.println("Annotation value: " + annotation.value()); } else { System.out.println("Annotation not available at runtime."); } } }
When to Use
Use retention policies to control how annotations behave in your Java programs. If you want annotations only for documentation or compile-time checks, use SOURCE. For tools that process class files but don't need annotations at runtime, use CLASS. When your program needs to read annotations during execution, for example in frameworks or libraries that use reflection, use RUNTIME.
Real-world examples include:
- Using
RUNTIMEretention for dependency injection frameworks to detect annotations on classes or methods. - Using
SOURCEretention for annotations that generate code or warnings during compilation. - Using
CLASSretention for annotations that affect bytecode but don't need runtime access.
Key Points
- RetentionPolicy.SOURCE: Annotation discarded after compilation.
- RetentionPolicy.CLASS: Annotation in class file but not at runtime.
- RetentionPolicy.RUNTIME: Annotation available at runtime via reflection.
- Retention policy is set using
@Retentionannotation. - Choosing the right retention affects performance and functionality.