注释保留策略:声明“SOURCE"或“CLASS"有什么真正的好处? [英] Annotation retention policy: what real benefit is there in declaring `SOURCE` or `CLASS`?

查看:32
本文介绍了注释保留策略:声明“SOURCE"或“CLASS"有什么真正的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 Java 注释有三种保留策略:

I know there are three retention policies for Java annotations:

CLASS:注解会被编译器记录在类文件中,但在运行时不需要被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.

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

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.

虽然我了解他们的使用场景,但我不明白为什么指定保留策略存在如此重要的事情.

And although I understand their usage scenarios, I don't get why it is such an important thing to specify the retention policy that retention policies exist at all.

我的意思是,为什么不是所有的注释都保存在运行时?它们是否会生成如此多的字节码/占用如此多的内存,以至于剥离那些未声明为 RUNTIME 的字节码确实会产生如此大的不同?

I mean, why aren't all the annotations just kept at runtime? Do they generate so much bytecode / occupy so much memory that stripping those undeclared as RUNTIME does make that much difference?

推荐答案

真正回答这个问题:减少依赖.如果之间没有区别,例如SOURCE 和 RUNTIME,类的用户"必须提供注释来自的所有依赖项.因此,仅因为 IDE (SOURCE) 使用了该注释,就必须在运行时提供 jar - 这是不必要的.如果您尝试从一个类中获取注解,而没有提供实际提供注解的 jar,您将得到一个类未找到异常.

To actually answer the question: to reduce dependencies. If there would be no distinction between e.g. SOURCE and RUNTIME, the "user" of the classes would have to provide all the dependencies the annotations come from. So only because that annotation is used by the IDE (SOURCE), the jar would have to be provided during runtime - which is unnecessary. If you try to get annotations from a class, where no jar is provided that actually provides the annotation, you will get a class not found exception.

这篇关于注释保留策略:声明“SOURCE"或“CLASS"有什么真正的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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