【Annotation】@Retention meta-annotation

@RetentionIt 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. @RetentionTheir purpose is to tell the compiler how to process annotations.

@RetentionThere are three values, namely RetentionPolicy.SOURCE, RetentionPolicy.CLASSand 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.RUNTIMEso 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.

Guess you like

Origin blog.csdn.net/weixin_45188218/article/details/135365174