java.lang.SuppressWarnings是J2SE 5.0中标准的Annotation型态之一,它对编译器说明某个方法中若有警示讯息,则加以抑制,不用在编译完成后出现警讯。
在这边到说明SuppressWarnings的功能,考虑下面这个类别:
import java.util.*; public class SomeObject { public void doSomething() { Map map = new HashMap(); map.put("some", "thing"); } }
在J2SE 5.0中加入了集合对象的Generics支持,并建议您明确的指定集合对象将内填的对象之型态,在上面这个类别中使用Map时并没有指定内填对象之型 别,在编译时会出现以下的讯息:
Note: SomeObject.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
在编译时一并指定-Xlint:unchecked可以看到警示的细节:
SomeObject.java:7: warning: [unchecked] unchecked call to put(K,V) as a member o f the raw type java.util.Map map.put("some", "thing"); ^ 1 warning
如果您想让编译器忽略这些细节,则可以如下使用SuppressWarnings这个Annotation:
import java.util.*; public class SomeObject { @SuppressWarnings(value={"unchecked"}) public void doSomething() { Map map = new HashMap(); map.put("some", "thing"); } }
这么一来,编译器将忽略掉"unckecked"的警讯,您也可以指定忽略多个警讯:
@SuppressWarnings(value={"unchecked", "deprecation"})