5

我正在尝试使用@Deprecated 注释。@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:警告:[deprecation] OtherClass 中的 theOldWay() 已被弃用

    thatClass.theOldWay();
             ^

1 个警告

4

2 回答 2

5

From the 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.

Your example is an example of the last condition: you're only using the deprecated method from the same outermost class as the deprecated method.

于 2012-10-28T11:00:05.127 回答
0

Deprecation Doesn't always trigger warnings. You have to manage Deprecation logic in your framework/application.

From 1.5 JavaDoc:

NOTE: The Java Language Specification requires compilers to issue warnings when classes, methods, or fields marked with the @Deprecated annotation are used. Compilers are not required by the Java Language Specification to issue warnings when classes, methods, or fields marked with the @deprecated Javadoc tag are accessed, although the Sun compilers currently do so. However, there is no guarantee that the Sun compiler will always issue such warnings.

于 2012-10-28T10:55:53.753 回答