为什么RetentionPolicy.RUNTIME用于@Deprecated注释



以下是@Deprecated注释的文档。

/**
 * A program element annotated @Deprecated is one that programmers
 * are discouraged from using, typically because it is dangerous,
 * or because a better alternative exists.  Compilers warn when a
 * deprecated program element is used or overridden in non-deprecated code.
 *
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}

我的问题是:@Deprecated(一个标记注释)是程序员用来指示这个方法/字段/包。。。则为什么RetentionPolicy被设置为RUNTIME为什么不使用RetentionPolicy.CLASS

Java中的反射可用于在运行时读取类的注释。如果使用RetentionPolicy.CLASS,则@Deprecated注释将不可用于这样读取。

例如,反射程序可能读入用户提供的类,并在没有任何参数的情况下执行所有不推荐使用的静态方法。也许有人能想出一个比这更好的例子。单元测试框架可能会利用它的一些原因。

最新更新