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

查看:101
本文介绍了批注保留策略:声明`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.

运行时间:注释将由编译器记录在类文件中,并在运行时由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天全站免登陆