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.
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));}}
SourceRetentionAnnotation
function to define the retention policy of the annotation as SOURCE.
Test
function to create a class and annotate it with SourceRetentionAnnotation.
Test
class.Test
class using the getAnnotations()
method.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.