Java 7中简化的可变参数方法调用 [英] Simplified Varargs Method Invocation in Java 7

查看:170
本文介绍了Java 7中简化的可变参数方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 7中,您可以选择放置 @SafeVarargs 注释来抑制编译具有不可变varargs参数的方法时得到的警告。项目币的提案规定,注释应该是当该方法确保只有与varargs参数相同类型的元素存储在varargs数组中时才使用。



什么是非安全方法的示例?

解决方案

例如, 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]
}

通过@SafeVarargs标记方法,编译器,你没有做任何调皮的事情。






但是我们怎么能在[1 ]开始? Java不允许通用数组的创建!



通用数组创建的唯一可行方式是调用可变参数方法

  foo(list_int_1,list_int_2)

然后数组调用者无法访问,无论如何,调用者无法做到这一点,不管怎样 foo()与数组混淆。



但是你想一想,它是创建泛型数组的后门

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

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

和泛型数组literal

  @SafeVarargs 
static< E> E []数组(E ...数组)
{
返回数组;
}

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

所以我们可以创建泛型数组......愚蠢的Java,试图阻止我们这样做。


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. 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.

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]

<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.


But how in hell can we get a generic array at [1] to start with? Java doesn't allow generic array creation!

The only sanctioned way of generic array creation is when calling a vararg method

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.

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 7中简化的可变参数方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆