Java 7 中简化的 Varargs 方法调用
在 Java 7 中,您可以选择放置 @SafeVarargs 注释来抑制在编译具有不可具体化的 varargs 参数的方法时收到的警告。 Project Coin 的提案规定注释应该是当该方法确保仅与 varargs 参数类型相同的元素存储在 varargs 数组中时使用。
非安全方法的例子是什么?
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?
例如,
foo()
不安全,它可能会在数组中存储非 T,从而导致 [2] 出现问题通过使用 @SafeVarargs 标记该方法,您向编译器保证您没有这样做任何像这样顽皮的事情。
但是我们到底如何才能在 [1] 处获得一个通用数组呢? Java 不允许创建通用数组!
创建通用数组的唯一受认可的方法是,当调用 vararg 方法
时,调用者无法访问该数组,调用者无论如何都无法执行 [2],无论
foo()
怎样与阵列混乱。但你想一想,它是创建泛型数组
和泛型数组文字的
后门所以我们可以毕竟创建泛型数组......愚蠢的Java,试图阻止我们不要这样做。
For example,
foo()
is not safe, it may store non-T in the array, causing problem at [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
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
and generic array literal
So we can create generic array after all... Silly Java, trying to prevent us from doing that.