Annotation retention policy: what real benefit is there in declaring `SOURCE` or `CLASS`?

前端 未结 2 1541
野的像风
野的像风 2021-01-21 17:23

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 re

相关标签:
2条回答
  • 2021-01-21 18:11

    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.

    0 讨论(0)
  • 2021-01-21 18:24

    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.

    Take a look at this post/answer Annotation SOURCE Retention Policy

    0 讨论(0)
提交回复
热议问题