Java @SuppressWarnings Annotation – Java @SuppressWarnings注释

最后修改: 2019年 1月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll have a look at how to use the @SuppressWarnings annotation.

在这个快速教程中,我们将看看如何使用@SuppressWarnings注释。

2. @SuppressWarnings Annotation

2.@SuppressWarnings 注释

Compiler warning messages are usually helpful. Sometimes warnings can get noisy, though.

编译器警告信息通常是有帮助的。不过,有时警告会变得很嘈杂。

Especially when we can’t or don’t want to address them:

特别是当我们不能或不想解决这些问题时。

public class Machine {
    private List versions;

    public void addVersion(String version) {
        versions.add(version);
    }
}

The compiler will issue a warning about this method. It’ll warn that we’re using a raw-typed collection. If we don’t want to fix the warning, then we can suppress it with the @SuppressWarnings annotation.

编译器会对这个方法发出一个警告。它将警告我们正在使用一个原始类型的集合。如果我们不想修复这个警告,那么我们可以用@SuppressWarnings注解来抑制它

This annotation allows us to say which kinds of warnings to ignore. While warning types can vary by compiler vendor, the two most common are deprecation and unchecked.

这个注解允许我们说明要忽略哪些类型的警告。虽然警告类型可能因编译器厂商而不同,最常见的两种是递减未检查

deprecation tells the compiler to ignore when we’re using a deprecated method or type.

deprecation告诉编译器,当我们使用一个废弃的方法或类型时,要忽略。

unchecked tells the compiler to ignore when we’re using raw types.

unchecked告诉编译器,当我们使用原始类型时,可以忽略。

So, in our example above, we can suppress the warning associated with our raw type usage:

因此,在我们上面的例子中,我们可以抑制与我们的原始类型用法有关的警告

public class Machine {
    private List versions;

    @SuppressWarnings("unchecked")
    // or
    @SuppressWarnings({"unchecked"})
    public void addVersion(String version) {
        versions.add(version);
    }
}

To suppress a list of multiple warnings, we set a String array containing the corresponding warning list:

为了抑制多个警告列表,我们设置一个String数组,包含相应的警告列表。

@SuppressWarnings({"unchecked", "deprecated"})

3. Conclusion

3.总结

In this guide, we saw how we can use the @SuppressWarnings annotation in Java.

在本指南中,我们看到如何在Java中使用@SuppressWarnings注解。

The full source code for the examples can be found over on GitHub.

这些例子的完整源代码可以在GitHub上找到