注释来源保留政策

发布于 2024-12-14 15:09:28 字数 306 浏览 3 评论 0原文

来自 Java 文档:

类: 注释将由编译器记录在类文件中,但不需要在运行时由 VM 保留。

运行时间: 注解将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取它们。

来源: 注释将被编译器丢弃。

我理解 RUNTIME (为了使用带有反射的注释)和 CLASS (对于编译器)的用法,但我不明白什么时候可以使用它

@Retention(RetentionPolicy.SOURCE)

你能解释一下吗?

From the Java doc:

CLASS:
Annotations are to be recorded in the class file by the compiler but need not be retained by the VM at run time.

RUNTIME:
Annotations are to be recorded in the class file by the compiler and retained by the VM at run time, so they may be read reflectively.

SOURCE:
Annotations are to be discarded by the compiler.

I understand the usages of RUNTIME (in order to use annotation with reflection) and CLASS (for the compiler) but I don't understand when it can be usefull to use

@Retention(RetentionPolicy.SOURCE)

Can you explain?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

荒芜了季节 2024-12-21 15:09:28

像 @SuppressWarnings、@Override 之类的东西是编译器使用的注释 - 在运行时不需要。对于那些 RetentionPolicy.SOURCE 来说是有意义的。注释也可以用来生成代码(看看Spring ROO)——运行时也不需要这样的注释。

Things like @SuppressWarnings, @Override are annotations used by the compiler - not needed at runtime. For those RetentionPolicy.SOURCE would make sense. Also annotations can be used to generate code (look at Spring ROO) - such annotation are also not required at run time.

溺深海 2024-12-21 15:09:28

这个答案非常有道理 - https://stackoverflow.com/a/43910948/3009968

您不希望包含依赖项,即使在编译代码之前就已经实现了所需的效果。例如@SuppressWarnings

您不希望包含编译器用来生成代码但在运行时根本不需要的依赖项。例如,正如之前的答案中已经提到的 -spring roo

This answer makes perfect sense - https://stackoverflow.com/a/43910948/3009968.

You would not like to include a dependency, the desired effects of which are realized even before the code is compiled. E.g. @SuppressWarnings

You would not like to include a dependency which is used by compiler to let's say generate code but not at all required during runtime. E.g. as mentioned already in previous answer -spring roo.

月隐月明月朦胧 2024-12-21 15:09:28

RetentionPolicy.CLASS - 定义的注释将存储在 .class 文件中,但在运行时不可用。如果您根本不指定任何保留策略,则这是默认保留策略。

RetentionPolicy.SOURCE - 构建代码时,编译器将忽略定义的注释。因此,注释仅在源代码中可用,在 .class 文件中不可用,在运行时也不可用。

RetentionPolicy.CLASS - The defined annotation will be stored in the .class file, but not available at runtime. This is the default retention policy if you do not specify any retention policy at all.

RetentionPolicy.SOURCE - The defined annotation will be ignored by the compiler when building the code. So the annotation is only available in the source code, and not in the .class files, and not at runtime too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文