免责声明:我知道 @Deprecated
的含义和目的.
@Deprecated
的定义注释在 Java 的源代码中看起来像这样:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
我理解目标值为 CONSTRUCTOR
的目的, FIELD
, TYPE
, METHOD
和 PACKAGE
.
但是,将方法参数或局部变量标记为@Deprecated
是什么意思? ?
奇怪的是,下面的示例编译时没有任何警告。
interface Doable {
void doIt(@Deprecated Object input);
}
class Action implements Doable {
@Override
public void doIt(@Deprecated Object input) {
String string = String.valueOf(input); // no warning!
@Deprecated
String localVariable = "hello";
System.out.println("Am I using a deprecated variable?" + localVariable); // no warning!
}
}
这是他们将来可能打算实现的东西吗?
FWIW,我在 Ubuntu 12.04 64 位上使用 JDK 1.7.0_11。无论我从 Eclipse 还是命令行运行程序,结果都是一样的。
对于 @Deprecated
的正常使用,编译器会发出警告。 ,例如使用 java.util.Date
的弃用构造函数之一类(class)。只是为了证明我没有错误的终端或设置,这里是输出:
$ javac com/adarshr/Test.java -Xlint:deprecation
com/adarshr/Test.java:12: warning: [deprecation] Date(int,int,int) in Date has been deprecated
new Date(2013, 1, 31);
^
1 warning
$
$ javac -version
javac 1.7.0_11
最佳答案
What does it mean to mark a method parameter or a local variable as
@Deprecated
?
它有the same meaning as when applied to any other element:
A program element annotated
@Deprecated
is one that programmers are discouraged from using, typically because it is dangerous, or because a better alternative exists. Compilers warn when a deprecated program element is used or overridden in non-deprecated code.
为什么编译器不忽略 Java 7 中不推荐使用的参数和字段的警告?
Because that's exactly what the JLS (§ 9.6.3.6) dictates.
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")
; orThe use and declaration are both within the same outermost class.
Use of the
@Deprecated
annotation on a local variable declaration or on a parameter declaration has no effect.
(强调)
关于java - @Deprecated 对方法参数和局部变量意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627313/