Java Annotations - looking for an example of RetentionPolicy.CLASS

后端 未结 4 1361
后悔当初
后悔当初 2020-12-14 16:56

according to Java Annotation API:

  • RetentionPolicy.CLASS Annotations are to be recorded in the class file by the compiler but nee

4条回答
  •  半阙折子戏
    2020-12-14 17:52

    Minimal example

    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    
    @Retention(RetentionPolicy.CLASS)
    @interface RetentionClass {}
    
    @Retention(RetentionPolicy.RUNTIME)
    @interface RetentionRuntime {}
    
    public static void main(String[] args) {
        @RetentionClass
        class C {}
        assert C.class.getAnnotations().length == 0;
    
        @RetentionRuntime
        class D {}
        assert D.class.getAnnotations().length == 1;
    }
    

    If we use javap on the annotated classes, we see that the Retention.CLASS annotated class gets a RuntimeInvisible class attribute:

    #14 = Utf8               LRetentionClass;
    [...]
    RuntimeInvisibleAnnotations:
      0: #14()
    

    while Retention.RUNTIME annotation gets a RuntimeVisible class attribute:

    #14 = Utf8               LRetentionRuntime;
    [...]
    RuntimeVisibleAnnotations:
      0: #14()
    

    So the information is present on both cases in the bytecode.

    Therefore, Runtime.CLASS can be used to associate arbitrary metadata to a class which bytecode manipulation tools can use, without interfering with runtime-visible behavior.

    Examples on GitHub for you to play with.

提交回复
热议问题