我正在尝试使用 @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/