Java Annotation @Retention
The @Retention
annotation is a standard Java annotation that is used to specify the retention policy for an annotation.
The retention policy determines how long an annotation should be retained for, and can be one of three options: SOURCE
, CLASS
, or RUNTIME
.
SOURCE
- The annotation is retained only in the source code and is discarded during compilation.CLASS
- The annotation is retained in the compiled bytecode but is not accessible at runtime.RUNTIME
- The annotation is retained in the compiled bytecode and is accessible at runtime through reflection.
Here is an example of how to use the @Retention
annotation:
@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { // annotation elements }
In this example, the MyAnnotation
annotation is annotated with @Retention
to specify that it should be retained at runtime. The RetentionPolicy.RUNTIME
parameter specifies the retention policy.
When you use the @Retention
annotation, it is important to choose the correct retention policy for your annotation. If you want your annotation to be accessible at runtime through reflection, you should use RetentionPolicy.RUNTIME
. If you only need your annotation to be accessible at compile time, you can use RetentionPolicy.SOURCE
or RetentionPolicy.CLASS
.