关于@SuppressWarnings的使用

538 阅读4分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

在代码中 每次编译,经常会有很多警告信息, 影响对代码错误信息的过滤,使用@SuppressWarnings注解,可以消除指定的编译器警告问题

1 @SuppressWarnings的简介

@SuppressWarnings的作用是让编译器不产生警告信息. 从源码可知,该注解从JDK1.5版本开始使用,它支持在类,属性,方法,参数,构造,本地变量上使用.注解中只有一个变量value, 字符串数组类型,支持多个类型的警告.

/**
 * Indicates that the named compiler warnings should be suppressed in the
 * annotated element (and in all program elements contained in the annotated
 * element).  Note that the set of warnings suppressed in a given element is
 * a superset of the warnings suppressed in all containing elements.  For
 * example, if you annotate a class to suppress one warning and annotate a
 * method to suppress another, both warnings will be suppressed in the method.
 *
 * <p>As a matter of style, programmers should always use this annotation
 * on the most deeply nested element where it is effective.  If you want to
 * suppress a warning in a particular method, you should annotate that
 * method rather than its class.
 *
 * @author Josh Bloch
 * @since 1.5
 * @jls 4.8 Raw Types
 * @jls 4.12.2 Variables of Reference Type
 * @jls 5.1.9 Unchecked Conversion
 * @jls 5.5.2 Checked Casts and Unchecked Casts
 * @jls 9.6.3.5 @SuppressWarnings
 */
// 类, 字段, 方法, 函数入参, 构造,局部变量
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
    /**
     * The set of warnings that are to be suppressed by the compiler in the
     * annotated element.  Duplicate names are permitted.  The second and
     * successive occurrences of a name are ignored.  The presence of
     * unrecognized warning names is <i>not</i> an error: Compilers must
     * ignore any warning names they do not recognize.  They are, however,
     * free to emit a warning if an annotation contains an unrecognized
     * warning name.
     *
     * <p> The string {@code "unchecked"} is used to suppress
     * unchecked warnings. Compiler vendors should document the
     * additional warning names they support in conjunction with this
     * annotation type. They are encouraged to cooperate to ensure
     * that the same names work across multiple compilers.
     * @return the set of warnings to be suppressed
     */
    String[] value();
}

常见使用的类型:

  • 单类型警告 如: @SuppressWarnings("unchecked") 抑制没有进行类型检查操作的警告
  • 多类型警告 如: @SuppressWarnings("unchecked","unused") 抑制没有进行类型检查操作和没被使用过的代码的警告
  • 所有类型警告 如: @SuppressWarnings("all") 抑制所有警告

警告的关键字清单:

关键字说明
allto suppress all warnings (抑制所有警告)
boxingto suppress warnings relative to boxing/unboxing operations (抑制装箱、拆箱操作时候的警告)
castto suppress warnings relative to cast operations (抑制映射相关的警告)
dep-annto suppress warnings relative to deprecated annotation (抑制启用注释的警告)
deprecationto suppress warnings relative to deprecation (抑制过期方法警告)
fallthroughto suppress warnings relative to missing breaks in switch statements (抑制确在switch中缺失breaks的警告)
finallyto suppress warnings relative to finally block that don’t return (抑制finally模块没有返回的警告)
hidingto suppress warnings relative to locals that hide variable(抑制相对于隐藏变量的局部变量的警告)
incomplete-switchto suppress warnings relative to missing entries in a switch statement (enum case)(忽略没有完整的switch语句)
nlsto suppress warnings relative to non-nls string literals( 忽略非nls格式的字符)
nullto suppress warnings relative to null analysis( 忽略对null的操作)
rawtypesto suppress warnings relative to un-specific types when using generics on class params( 使用generics时忽略没有指定相应的类型,即没有传递带有泛型的参数)
restrictionto suppress warnings relative to usage of discouraged or forbidden references( 抑制禁止使用劝阻或禁止引用的警告)
serialto suppress warnings relative to missing serialVersionUID field for a serializable class( 忽略在serializable类中没有声明serialVersionUID变量)
static-accessto suppress warnings relative to incorrect static access( 抑制不正确的静态访问方式警告)
synthetic-accessto suppress warnings relative to unoptimized access from inner classes( 抑制子类没有按最优方法访问内部类的警告)
uncheckedto suppress warnings relative to unchecked operations( 抑制没有进行类型检查操作的警告)
unqualified-field-accessto suppress warnings relative to field access unqualified( 抑制没有权限访问的域的警告)
unusedto suppress warnings relative to unused code( 抑制没被使用过的代码的警告)

2 @SuppressWarnings的使用

    // 抑制未使用警告
    @SuppressWarnings("unused")
    public void test1(){
        try {
            // 未使用警告
            String s = "";
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 抑制未进行类型检查操作警告 未指定相应的类型警告 未使用警告
    @SuppressWarnings({"unchecked","rawtypes","unused"})
    public void test2(){
        try {
            // 未使用警告
            String s = "";
            // 未进行类型检查操作警告 未指定相应的类型警告
            List items = new ArrayList();
            items.add("李白");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 抑制所有警告
    @SuppressWarnings({"all"})
    public void test3(){
        try {
            String s = "";
            List items = new ArrayList();
            items.add("李白");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

参考文章:

www.cnblogs.com/EasonJim/p/…

my.oschina.net/u/2433960/b…

www.jianshu.com/p/b41277be4…