当你声明
public static void foo(List... bar)编译器将其转换为
public static void foo(List[] bar) then
public static void foo(List[] bar)
然后会出现危险,你会错误地将不正确的值分配到列表中,编译器不会触发任何错误。 例如,如果T是一个String那么以下代码将无错地编译,但在运行时会失败:
// First, strip away the array type (arrays allow this kind of upcasting) Object[] objectArray = bar; // Next, insert an element with an incorrect type into the array objectArray[0] = Arrays.asList(new Integer(42)); // Finally, try accessing the original array. A runtime error will occur // (ClassCastException due to a casting from Integer to String) T firstElement = bar[0].get(0);
如果您查看了方法以确保它不包含此类漏洞,则可以使用@SafeVarargs进行注释以取消警告。 对于接口,使用@SuppressWarnings("unchecked") 。
如果您收到此错误消息:
可变参数法可能会导致不可保证的可变参数的堆污染
你确定你的使用是安全的,那么你应该使用@SuppressWarnings("varargs")来代替。 请参阅@SafeVarargs此方法的适当注释吗? 和https://stackoverflow.com/a/14252221/14731第二类错误的一个很好的解释。
参考文献: