RetentionPolicy CLASS 与 RUNTIME [英] RetentionPolicy CLASS vs. RUNTIME

查看:26
本文介绍了RetentionPolicy CLASS 与 RUNTIME的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

无论如何都可以在运行时访问.

这不是 javadoc 所说的:>

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

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

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

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

What is the practical difference between RetentionPolicy.CLASS and RetentionPolicy.RUNTIME?

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

解决方案

both may be accessed at the run-time anyway.

That's not what the javadoc says:

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.

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

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.

Ironically, CLASS is the default behaviour.

这篇关于RetentionPolicy CLASS 与 RUNTIME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆