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:

  1. SOURCE
  2. CLASS

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 RuntimeRetentionAnnotation annotation which is annotated with the retention policy of the annotation as RUNTIME.
  • Lines 9–10: We create the Test class and annotate it with RuntimeRetentionAnnotation.
  • Line 14: We create an instance of the Test class names as test.
  • Line 15: We use the getAnnotations() method to get all annotations of the Test class.
  • 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

Copyright ©2025 Educative, Inc. All rights reserved