Annotation retention policy: what real benefit is

2020-04-18 03:33发布

I know there are three retention policies for Java annotations:

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: 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.

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?

2条回答
Summer. ? 凉城
2楼-- · 2020-04-18 03:59

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.

查看更多
小情绪 Triste *
3楼-- · 2020-04-18 04:03

Retention policy SOURCE is to aid IDEs, compilers and possibly code/doc generators to take advantage of annotations. These annotation do not make up part of compiled class and are discarded by compiler so not available during runtime.

For example, annotation java.lang.SuppressWarnings tells compiler not to report certain warnings.

Annotations to generate documentation can be of retention policy SOURCE.

查看更多
登录 后发表回答