不同的保留策略如何影响我的注释?

xde*_*000 167 java annotations

以明确的方式有谁能解释之间的实际差别java.lang.annotation.RetentionPolicy常数SOURCE,CLASSRUNTIME

我也不完全确定"保留注释"这个短语是什么意思.

Fav*_*ius 200

  • RetentionPolicy.SOURCE:在编译期间丢弃.编译完成后,这些注释没有任何意义,因此它们不会写入字节码.
    示例:@Override,@SuppressWarnings

  • RetentionPolicy.CLASS:在课堂加载期间丢弃.在进行字节码级后处理时很有用.有点令人惊讶的是,这是默认值.

  • RetentionPolicy.RUNTIME: 不要丢弃.注释应该可以在运行时进行反射.例:@Deprecated

来源: 旧网址已经死了,现在是 hunter_meta,取而代之的是hunter-meta-2-098036.如果这种情况发生了变化,我会上传页面的图像.

图像(右键单击并选择"在新标签/窗口中打开图像") 在此输入图像描述

  • 感谢您的引用,这里最有趣的是“RetentionPolicy.CLASS”的用例 (2认同)
  • 你能解释一下为什么 RetentionPolicy.class 很有趣/令人惊讶的是默认吗? (2认同)

ewe*_*nli 52

根据你对类反编译的评论,我认为它应该如何工作:

  • RetentionPolicy.SOURCE:不会出现在反编译的类中

  • RetentionPolicy.CLASS:出现在反编译的类中,但在运行时不能用反射检查 getAnnotations()

  • RetentionPolicy.RUNTIME:出现在反编译的类中,可以在运行时使用反射进行检查 getAnnotations()

  • RetentionPolicy.CLASS 有任何用例吗? (2认同)

Cir*_*四事件 19

最小的可运行示例

语言水平:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.SOURCE)
@interface RetentionSource {}

@Retention(RetentionPolicy.CLASS)
@interface RetentionClass {}

@Retention(RetentionPolicy.RUNTIME)
@interface RetentionRuntime {}

public static void main(String[] args) {
    @RetentionSource
    class B {}
    assert B.class.getAnnotations().length == 0;

    @RetentionClass
    class C {}
    assert C.class.getAnnotations().length == 0;

    @RetentionRuntime
    class D {}
    assert D.class.getAnnotations().length == 1;
}
Run Code Online (Sandbox Code Playgroud)

字节码级别:使用javap我们观察带Retention.CLASS注释的类获取RuntimeInvisible类属性:

#14 = Utf8               LRetentionClass;
[...]
RuntimeInvisibleAnnotations:
  0: #14()
Run Code Online (Sandbox Code Playgroud)

while Retention.RUNTIME注释获取RuntimeVisible类属性:

#14 = Utf8               LRetentionRuntime;
[...]
RuntimeVisibleAnnotations:
  0: #14()
Run Code Online (Sandbox Code Playgroud)

并且Runtime.SOURCE注释.class没有得到任何注释.

GitHub上的示例供您使用.


wah*_*cse 7

保留策略:保留策略确定在什么时候丢弃注释。它是使用 Java 的内置注释指定的:@Retention[关于]

1.SOURCE: annotation retained only in the source file and is discarded
          during compilation.
2.CLASS: annotation stored in the .class file during compilation,
         not available in the run time.
3.RUNTIME: annotation stored in the .class file and available in the run time.
Run Code Online (Sandbox Code Playgroud)