Annotations are used to attach metadata to program elements like classes, methods, and instances.
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.
@Retention(RetentionPolicy.CLASS)
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));}}
ClassRetentionAnnotation
where we define the retention policy of the annotation as CLASS
.Test
class and annotate it with ClassRetentionAnnotation
.Test
class named test
.Test
class using the getAnnotations()
method.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.