似乎在编译期间不考虑@SuppressWarnings

Omk*_*kar 3 java

为了试验@SuppressWarnings注释,我编写了以下示例程序:

public class Test {

    public static void main(String[] args) {
        @SuppressWarnings("unchecked")
        Set set = new HashSet();
        Integer obj = new Integer(100);
        set.add(obj);
    }

}
Run Code Online (Sandbox Code Playgroud)

但即使在这个注释之后,我在控制台上得到以下输出:

Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Run Code Online (Sandbox Code Playgroud)

如果我在main方法声明之前移动注释,则会禁止警告.这里缺少什么?

谢谢.

chr*_*ke- 5

编译器告诉您Recompile with -Xlint:unchecked for details.这样做提供了上下文:当您使用时注释声明@SuppressWarnings,您也将泛型方法称为原始操作.

Test.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type Set
        set.add(obj);
               ^
  where E is a type-variable:
    E extends Object declared in interface Set
Run Code Online (Sandbox Code Playgroud)

如果您将整个方法移动@SuppressWarnings到该main方法,警告就会消失.

JLS部分@SuppressWarnings说:

如果程序声明使用注释@SuppressWarnings[...]进行注释,那么如果由于带注释的声明或其任何部分而生成该警告,则Java编译器不得报告任何警告[...] .(我的大胆)

您的示例代码仅抑制局部变量声明,而不是方法声明.

更新

奇怪的是,即使你明显得到的信息在技术上也不是警告,而是一张便条.编译-Werror工作就好了.使用-Xlint选项会使其成为警告.