Java 似乎在编译期间不考虑@SuppressWarnings
为了试验Java 似乎在编译期间不考虑@SuppressWarnings,java,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); } } 但即使在
@SuppressWarnings
注释,我编写了以下示例程序:
public class Test {
public static void main(String[] args) {
@SuppressWarnings("unchecked")
Set set = new HashSet();
Integer obj = new Integer(100);
set.add(obj);
}
}
但即使在这个注释之后,我在控制台上也会得到以下输出:
Note: Test.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
如果我在main方法声明之前移动注释,那么警告将被抑制。
这里少了什么
谢谢。编译器告诉您使用-Xlint:unchecked重新编译
,以获取详细信息。
这样做提供了上下文:当您使用@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
如果将
@SuppressWarnings
作为一个整体移动到main
方法,警告将消失
说:
如果程序声明是用注释
@SuppressWarnings
[…]注释的,那么Java编译器不得报告任何警告[…],如果该警告是由注释声明或其任何部分生成的。(我的粗体)
示例代码仅抑制局部变量声明,而不抑制方法声明
更新
奇怪的是,就连你收到的信息从技术上来说也不是警告,而是一张便条。使用
-Werror
编译效果很好。使用-Xlint
选项会使其成为警告。以下是没有编译时警告的程序:
import java.util.*;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args){
Set set = new HashSet();
Integer obj = new Integer(100);
set.add(obj);
}
}
请记住,这只是用于注释的实验。这里理想的解决方案是使用泛型而不是原始类型。
@SuppressWarnings
值取决于编译器。例如,Eclipse将使用rawtypes
来抑制原始类型警告。@SotiriosDelimanolis我使用以下Java环境:Java版本“1.8.0_20”Java(TM)SE运行时环境(构建1.8.0_20-b26)Java热点(TM)64位服务器VM(构建25.20-b23,混合模式)尝试“rawtypes”。“unchecked”用于未经检查的强制转换(您没有)。使用“rawtypes”和“all”选项进行检查,但结果相同:(问题是抑制的范围。正在调查。谢谢。这解决了问题。但理想情况下,警告抑制应该发生在尽可能低的范围内。我认为此注释可以在进行原始类型方法调用之前放置。但这似乎是不可能的。其目的是避免使用原始类型。如果声明 Set=…
则根本不需要注释。