Java基础 - 常用注解@SuppressWarings

一、概述

java.lang.SuppressWarnings是J2SE5.0中标准的Annotation之一。可以标注在类,字段、方法、构造方法以及局部变量上。

@SuppressWarings作用:告诉编译器忽略指定的警告,不用在编译完成后出现警告信息。

@SuppressWarings使用:

  1. @SuppressWarnings(“”)
  2. @SuppressWarnings({})
  3. @SuppressWarnings(value={})

value -将由编译器在注释的元素中取消显示的警告集。允许使用重复的名称。忽略第二个和后面出现的名称。出现未被识别的警告名 不是错误:编译器必须忽略无法识别的所有警告名。但如果某个注释包含未被识别的警告名,那么编译器可以随意发出一个警告。

各编译器供应商应该将它们所支持的警告名连同注释类型一起记录。鼓励各供应商之间相互合作,确保在多个编译器中使用相同的名称。

常用注解演示

  • @SuppressWarnings(“unchecked”)

    告诉编译器忽略unchecked警告信息,如使用List、ArrayList等未进行参数化产生的警告信息。

  • @SuppressWarnings(“serial”)

    告诉编译器忽略:The serializable class WmailCalendar does notdeclare a static final serialVersionUID field of type long信息。

  • @SuppressWarnings(“deprecation”)

    告诉编译器忽略使用注解@Deprecated警告信息

  • @SuppressWarnings(“unchecked”, “deprecation”)

    告诉编译器同时忽略unchecked和deprecation的警告信息。

二、 @SuppressWarings注解使用

2.1. 抑制单类型的警告

@SuppressWarnings("unchecked")
public void annotationDemo(String item){
  @SuppressWarnings("rawtypes")
   List items = new ArrayList();
   items.add(item);
}

2.2. 抑制多类型的警告

@SuppressWarnings(value={"unchecked", "rawtypes"})
public void annotationDemo(String item){
   List items = new ArrayList();
   items.add(item);
}

2.3. 抑制所有类型的警告

@SuppressWarnings(value={"all"})
public void annotationDemo(String item){
   List items = new ArrayList();
   items.add(item);
}

四、注解目标

通过 @SuppressWarnings 的源码可知,其注解目标为类、字段、函数、函数入参、构造函数和函数的局部变量。

建议注解应声明在最接近警告发生的位置。

五、抑制警告的关键字

08-25 16:28