Java @SafeVarargs Annotation – Java @SafeVargs 注释

最后修改: 2019年 1月 2日

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

1. Overview

1.概述

In this quick tutorial, we’ll have a look at the @SafeVarargs annotation.

在这个快速教程中,我们将看一下@SafeVargs注解。

2. The @SafeVarargs Annotation

2.@SafeVargs 注释

Java 5 introduced the concept of varargs, or a method parameter of variable length, as well as parameterized types.

Java 5引入了varargs的概念,即一个长度可变的方法参数,以及参数化类型。

Combining these can cause problems for us:

将这些东西结合起来会给我们带来问题。

public static <T> T[] unsafe(T... elements) {
    return elements; // unsafe! don't ever return a parameterized varargs array
}

public static <T> T[] broken(T seed) {
    T[] plant = unsafe(seed, seed, seed); // broken! This will be an Object[] no matter what T is
    return plant;
}

public static void plant() {
   String[] plants = broken("seed"); // ClassCastException
}

These problems are tricky for a compiler to confirm, and so it gives warnings whenever the two are combined, like in the case of unsafe:

这些问题对编译器来说是很棘手的,所以只要两者结合起来,它就会发出警告,比如在unsafe:的情况下。

warning: [unchecked] Possible heap pollution from parameterized vararg type T
  public static <T> T[] unsafe(T... elements) {

This method, if used incorrectly, like in the case of broken, will pollute an Object[] array into the heap instead of the intended type b.

这个方法,如果使用不当,就像在broken的情况下,会把一个Object[]数组污染到堆中,而不是预期的类型b

To squash this warning, we can add the @SafeVarargs annotation on final or static methods and constructors.

为了消除这个警告,我们可以在final或static方法和构造函数上添加@SafeVargs注解

@SafeVarargs is like @SupressWarnings in that it allows us to declare that a particular compiler warning is a false positive. Once we ensure our actions are safe, we can add this annotation:

@SafeVargs@SupressWarnings一样,它允许我们声明某个特定的编译器警告是一个错误的肯定。一旦我们确保我们的行动是安全的,我们就可以添加这个注解。

public class Machine<T> {
    private List<T> versions = new ArrayList<>();

    @SafeVarargs
    public final void safe(T... toAdd) {
        for (T version : toAdd) {
            versions.add(version);
        }
    }
}

Safe use of varargs is a tricky concept in and of itself. For more information, Josh Bloch has a great explanation in his book, Effective Java.

安全使用varargs本身就是一个棘手的概念。关于更多信息,Josh Bloch在他的书中有一个很好的解释,Effective Java

3. Conclusion

3.总结

In this quick article, we saw how to use the @SafeVarargs annotation in Java.

在这篇快速文章中,我们看到了如何在Java中使用@SafeVargs注解。

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

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