java - @Deprecated 对方法参数和局部变量意味着什么?

标签 java deprecated

免责声明:我知道 @Deprecated 的含义和目的.

@Deprecated的定义注释在 Java 的源代码中看起来像这样:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}

我理解目标值为 CONSTRUCTOR 的目的, FIELD , TYPE , METHODPACKAGE .

但是,将方法参数或局部变量标记为@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"); or

  • The 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/

相关文章:

java - 通过 ID 检索用户对象

java - Location.getLatitude 方法返回非精度 double ,这对 GPS 坐标不利

ruby-on-rails - alias_method_chain 已弃用 - Rails 5 升级

c - 如何防止客户端使用低于 v1.2 的 TLS 进行连接?

ios - 存档和取消存档数据 : SWIFT 4

java - 抑制 Java 中不推荐使用的导入警告

java - 为什么 boolean 变量不显示 false 的任何结果?

java - 关闭 log4j2 启动调试日志记录

java - Cucumber 在 4.7 中弃用了 Given/Then/When - 它们应该被什么取代?

java - 使用数学和流在 Java 8 中重新映射数组