What is RetentionPolicy.RUNTIME in Java?
As the name suggests, when an annotation should be discarded/destroyed, it depends on the RetentionPolicy in Java.
The @Retention meta-annotation can be applied to other annotations that decide how long the annotated type should be retained in the program’s lifetime as indicated by the @Retention annotation. The retention policy is set to CLASS if no retention policy is given on an annotation type definition.
Note: An annotation is a programming construct that attaches metadata to program elements like classes, methods, and instances.
There are multiple retention policies in Java. One such retention policy is RUNTIME. The other retention policies are as follows:
The RetentionPolicy.RUNTIME policy
Annotations marked with RetentionPolicy.RUNTIME are kept around until runtime, meaning they’ll be accessible in the runtime, source code, and class files.
Syntax
@Retention(RetentionPolicy.RUNTIME)
Example
import java.lang.annotation.*;import java.util.Arrays;@Retention(RetentionPolicy.RUNTIME)@interface RuntimeRetentionAnnotation {String metadata();}@RuntimeRetentionAnnotation(metadata = "this is a test class")class Test { }class Main{public static void main(String[] args) {Test test = new Test();Annotation[] annotations = test.getClass().getAnnotations();System.out.println("List of annotations at runtime - " + Arrays.toString(annotations));}}
Explanation
- Lines 4–7: We define the
RuntimeRetentionAnnotationannotation which is annotated with the retention policy of the annotation asRUNTIME. - Lines 9–10: We create the
Testclass and annotate it withRuntimeRetentionAnnotation. - Line 14: We create an instance of the
Testclass names astest. - Line 15: We use the
getAnnotations()method to get all annotations of theTestclass. - Line 16: We print the list of annotations.
Once the code is run, the Test class’s list of annotations will not be empty since the retention policy of the annotation is runtime. As a result, the RuntimeRetentionAnnotation is listed in the output.
Free Resources