java - 为什么 @Deprecated 注释不触发有关方法的编译器警告?

标签 java annotations

我正在尝试使用 @Deprecated annotation . @Deprecated 文档说:“当在非弃用代码中使用或覆盖已弃用的程序元素时,编译器会发出警告”。我认为这应该触发它,但它没有。 javac 版本 1.7.0_09 并使用和不使用 -Xlint 编译 -弃用。

public class TestAnnotations {

   public static void main(String[] args)
   {
      TestAnnotations theApp = new TestAnnotations();
      theApp.thisIsDeprecated();
   }

   @Deprecated
   public void thisIsDeprecated()
   {
      System.out.println("doing it the old way");
   }
}

编辑:根据下面 gd1 的评论,它仅在该方法位于另一个类中时才有效,我添加了第二个类。它确实在调用 theOldWay() 时发出警告:

public class TestAnnotations {

   public static void main(String[] args)
   {
      TestAnnotations theApp = new TestAnnotations();
      theApp.thisIsDeprecated();
      OtherClass thatClass = new OtherClass();
      thatClass.theOldWay();
   }

   @Deprecated
   public void thisIsDeprecated()
   {
      System.out.println("doing it the old way");
   }
}

class OtherClass {

   @Deprecated
   void theOldWay()
   {
      System.out.println("gone out of style");
   }


}

警告:

/home/java/TestAnnotations.java:10: warning: [deprecation] theOldWay() in OtherClass has been deprecated

    thatClass.theOldWay();
             ^

1 warning

最佳答案

来自Java Language Specification :

A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless:

  • The use is within an entity that is itself annotated with the annotation @Deprecated; or

  • The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); or

  • The use and declaration are both within the same outermost class.

您的示例是最后一个条件的示例:您仅使用与已弃用方法相同的最外层类中的已弃用方法。

关于java - 为什么 @Deprecated 注释不触发有关方法的编译器警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108112/

相关文章:

Java - 遍历数组节点

java - 从带注释的字段接收注释值

python - 将当前类作为返回类型注释

java - 启动后在JBoss上执行代码

java - Android @NonNull 的用处

当为 IntDef 字段分配错误值时,Android Studio 和 Lint 不会生成错误

java - 更新 jprogress-bar

java - Android NavigationView 菜单切换按钮

java - pom 中的 Maven 配置文件

java - 在 Android 中序列化一个 Intent ?