java RetentionPolicy CLASS 与 RUNTIME

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5971234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:45:44  来源:igfitidea点击:

RetentionPolicy CLASS vs. RUNTIME

javaannotations

提问by Dima

What is the practical difference between RetentionPolicy.CLASSand RetentionPolicy.RUNTIME?

RetentionPolicy.CLASS和之间的实际区别是RetentionPolicy.RUNTIME什么?

It looks like both are recorded into the bytecode and both may be accessed at the run-time anyway.

看起来两者都记录在字节码中,无论如何都可以在运行时访问。

回答by skaffman

both may be accessed at the run-time anyway.

无论如何,两者都可以在运行时访问。

That's not what the javadocsays:

这不是javadoc所说的:

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.

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

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

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

In practice, I'm not aware of any use-cases for CLASS. It would only be useful if you wanted to read the bytecode programmatically, as opposed to via the classloader API, but that's a very specialised case, and I don't know why you wouldn't just use RUNTIME.

实际上,我不知道CLASS. 它仅在您想以编程方式读取字节码时才有用,而不是通过类加载器 API,但这是一个非常特殊的情况,我不知道您为什么不只使用RUNTIME.

Ironically, CLASSis the default behaviour.

具有讽刺意味的是,这CLASS是默认行为。

回答by VladimirVip

@DebugLogin Hugo library uses Retention.CLASS

Hugo 库中的@DebugLog使用 Retention.CLASS