Scooter
Scooter

Reputation: 7061

Why isn't the @Deprecated annotation triggering a compiler warning about a method?

I am trying to use the @Deprecated annotation. The @Deprecated documentation says that: "Compilers warn when a deprecated program element is used or overridden in non-deprecated code". I would think this should trigger it, but it did not. javac version 1.7.0_09 and compiled using and not using -Xlint and -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");
   }
}

Edit: per the comment of gd1 below regarding it only working if the method is in another class, I added a second class. And it DOES WARN on the call to 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");
   }


}

The warning:

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

    thatClass.theOldWay();
             ^

1 warning

Upvotes: 7

Views: 1415

Answers (2)

JB Nizet
JB Nizet

Reputation: 691695

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.

Upvotes: 8

Evan P
Evan P

Reputation: 1817

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.

Upvotes: 0

Related Questions