What is RetentionPolicy.SOURCE in Java?

Overview

In Java, we use annotations to attach meta-data to program elements like classes, methods, and instances.

The RetentionPolicy.SOURCE function determines when an annotation is discarded. We apply @Retention as a meta-annotation to other annotations. The @Retention annotation 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.

Annotation with retention policy SOURCE is retained only with source code and discarded during compile time. We use SOURCE in scenarios where having the annotations is not needed after the compilation process is over. Hence, these annotations aren’t written to the bytecode.

Example

Let’s view an example of the usage of this annotation.

@Retention(RetentionPolicy.SOURCE)
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
@Retention(RetentionPolicy.SOURCE)
@interface SourceRetentionAnnotation {
String metadata();
}
@SourceRetentionAnnotation(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 use the SourceRetentionAnnotation function to define the retention policy of the annotation as SOURCE.
  • Lines 11–14: We use the Test function to create a class and annotate it with SourceRetentionAnnotation.
  • Line 19: We create an instance of the Test class.
  • 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 will be empty as the retention policy of the SourceRetentionAnnotation is source code only.

Free Resources