VOOZH about

URL: https://www.geeksforgeeks.org/java/java-retention-annotations/

⇱ Java @Retention Annotations - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java @Retention Annotations

Last Updated : 10 May, 2022

In Java, annotations are used to attach meta-data to a program element such as a class, method, instances, etc. Some annotations are used to annotate other annotations. These types of annotations are known as meta-annotations. @Retention is also a meta-annotation that comes with some retention policies. These retention policies determine at which point an annotation is discarded. There are three types of retention policies: SOURCE, CLASS, and RUNTIME.

  • RetentionPolicy.SOURCE: The annotations annotated using the SOURCE retention policy are discarded at runtime.
  • RetentionPolicy.CLASS: The annotations annotated using the CLASS retention policy are recorded in the .class file but are discarded during runtime. CLASS is the default retention policy in Java.
  • RetentionPolicy.RUNTIME: The annotations annotated using the RUNTIME retention policy are retained during runtime and can be accessed in our program during runtime.

Implementation:

Here we will be creating three custom annotations with retention policies such as SOURCE, CLASS, and RUNTIME. These custom annotations are later used to annotate three classes, namely A, B, and C. In the main method, we check if the annotations are attached to classes at runtime or not.

Example

 
 


Output
Number of annotations attached to class A at Runtime: 0
Number of annotations attached to class B at Runtime: 0
Number of annotations attached to class C at Runtime: 1
Annotation attached to class C: @RuntimeRetention(value="Runtime Retention")


 

Comment
Article Tags:
Article Tags: