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

时间:2012-10-28 10:40:58

标签: java annotations

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

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:警告:[弃用]   OtherClass中的OldWay()已被弃用

    thatClass.theOldWay();
             ^
     

1警告

2 个答案:

答案 0 :(得分:5)

来自Java Language Specification

  

Java编译器必须在类型时生成弃用警告,   声明用。注释的方法,字段或构造函数   使用注释@Deprecated(即重写,调用或   由名称引用),除非:

     
      
  • 使用在一个实体内,该实体本身用注释@Deprecated注释;或

  •   
  • 使用是在注释为使用注释@SuppressWarnings(“deprecation”)抑制警告的实体内;或

  •   
  • 使用和声明都在同一个最外层。

  •   

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

答案 1 :(得分:0)

弃用并不总是触发警告。您必须在框架/应用程序中管理Deprecation逻辑。

来自1.5 JavaDoc:

  

注意:Java语言规范要求编译器在使用标记有@Deprecated注释的类,方法或字段时发出警告。虽然Sun编译器目前这样做,但是当访问标记有@deprecated Javadoc标记的类,方法或字段时,Java语言规范不要求编译器发出警告。但是,无法保证Sun编译器始终会发出此类警告。