What is RetentionPolicy.CLASS in Java?

Annotations in Java

Annotations are used to attach metadata to program elements like classes, methods, and instances.

RetentionPolicy

The RetentionPolicy in Java determines the point at which an annotation should be discarded. @Retention is a meta-annotation that can be applied to other annotations. @Retention indicates how long the annotated type should be kept in the program’s lifecycle. The retention policy defaults to CLASS if no Retention policy is provided on an annotation type definition.

RetentionPolicy.CLASS

Annotations with RetentionPolicy.CLASS will be retained till code compilation but are discarded during the runtime. Annotations with CLASS will be written to byte code but will be discarded during the class loading time that makes it unavailable during runtime.

Syntax

@Retention(RetentionPolicy.CLASS)

Example

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
@Retention(RetentionPolicy.CLASS)
@interface ClassRetentionAnnotation {
String metadata();
}
@ClassRetentionAnnotation(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 6–9: We define an annotation named ClassRetentionAnnotation where we define the retention policy of the annotation as CLASS.
  • Lines 11–14: We create the Test class and annotate it with ClassRetentionAnnotation.
  • Line 19: We create an instance of the Test class named test.
  • Line 20: We get all annotations of the Test class using the getAnnotations() method.
  • Line 21: We print the list of annotations.

When the code above is run, the list of annotations of the Test class is empty because the retention policy of the ClassRetentionAnnotation is compile-time only.

Free Resources