@Retention
It is one of the meta-annotations in Java, used to specify the retention policy of annotations. Meta-annotations are annotations used to annotate other annotations. @Retention
Their purpose is to tell the compiler how to process annotations.
@Retention
There are three values, namely RetentionPolicy.SOURCE
, RetentionPolicy.CLASS
and RetentionPolicy.RUNTIME
.
RetentionPolicy.SOURCE
:
- Annotations are only retained at the source code level and are discarded at compile time . This means that the annotation information will not be included in the compiled class file (.class file). This retention policy is typically used when writing compile-time tools.
@Retention(RetentionPolicy.SOURCE) public @interface MyAnnotation { // annotation details }
RetentionPolicy.CLASS
:
- Annotations are retained at compile time and will be included in the compiled class file, but will be discarded at runtime . This is the default retention policy.
@Retention(RetentionPolicy.CLASS) public @interface MyAnnotation { // annotation details }
RetentionPolicy.RUNTIME
:
-
Annotations are retained at compile time and runtime , so annotation information can be obtained at runtime through reflection. This retention policy is typically used for custom annotations that need to be processed at runtime .
@Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { // annotation details }
When customizing annotations, you usually choose
RetentionPolicy.RUNTIME
so that the annotation information can be obtained through reflection at runtime. For example:@Retention(RetentionPolicy.RUNTIME) public @interface RpcApiEntry { // annotation details }
When processing custom annotations, choose an appropriate retention strategy based on specific needs.