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:
RetentionPolicy.RUNTIME
policyAnnotations marked with RetentionPolicy.RUNTIME
are kept around until runtime, meaning they’ll be accessible in the runtime, source code, and class files.
@Retention(RetentionPolicy.RUNTIME)
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));}}
RuntimeRetentionAnnotation
annotation which is annotated with the retention policy of the annotation as RUNTIME
.Test
class and annotate it with RuntimeRetentionAnnotation
.Test
class names as test
.getAnnotations()
method to get all annotations of the Test
class.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