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
RetentionPolicy CLASS vs. RUNTIME
提问by Dima
What is the practical difference between RetentionPolicy.CLASS
and 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, CLASS
is the default behaviour.
具有讽刺意味的是,这CLASS
是默认行为。