简体   繁体   English

Java 7中简化的Varargs方法调用

[英]Simplified Varargs Method Invocation in Java 7

In Java 7, you have the option to put a @SafeVarargs annotation to suppress the warning you get when compiling a method with a non-reifiable varargs parameter. 在Java 7中,您可以选择放置@SafeVarargs注释来抑制在使用不可重新生成的varargs参数编译方法时获得的警告。 Project Coin's proposal stipulates that the annotation should be used when the method ensures that only elements of the same type as the varargs parameter are stored in the varargs array. Project Coin的提议规定,当方法确保只有与varargs参数相同类型的元素存储在varargs数组中时,才应使用注释。

What would be an example of a non-safe method? 什么是非安全方法的例子?

For example, foo() is not safe, it may store non-T in the array, causing problem at [2] 例如, foo()不安全,它可能在数组中存储非T,导致问题[2]

<T extends List<?>> void foo(T... args)
{
    List<String>[] array2 = (List<String>[])args;
    array2[0] = a_list_of_string;
}

void test2()
{
    List<Integer>[] args = ...;   // [1]
    foo(args);
    Integer i = args[0].get(0);   // [2]
}

By marking the method with @SafeVarargs, you promise to compiler that you are not doing anything naughty like that. 通过使用@SafeVarargs标记方法,您向编译器保证您没有做任何顽皮的事情。


But how in hell can we get a generic array at [1] to start with? 但是我们怎么能在[1]开始使用通用数组呢? Java doesn't allow generic array creation! Java不允许创建通用数组!

The only sanctioned way of generic array creation is when calling a vararg method 通用数组创建唯一受到批准的方法是调用vararg方法

foo( list_int_1, list_int_2 )

then the array isn't accessible to caller, caller can't do [2] anyway, it doesn't matter how foo() messes with the array. 然后调用者无法访问该数组,调用者无论如何也无法做到[2], foo()如何与数组混淆并不重要。

But then you think about it, it is the backdoor to create generic array 但是你想一想,它创建通用数组的后门

@SafeVarargs
static <E> E[] newArray(int length, E... array)
{
    return Arrays.copyOf(array, length);
}

List<String>[] array1 = newArray(10);

and generic array literal 和通用数组文字

@SafeVarargs
static <E> E[] array(E... array)
{
    return array;
}

List<String>[] array2 = array( list1, list2 );

So we can create generic array after all... Silly Java, trying to prevent us from doing that. 所以我们毕竟可以创建通用数组......愚蠢的Java,试图阻止我们这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM