Safe Varargs

Joe Darcy joe.darcy at oracle.com
Tue Jan 25 10:40:33 PST 2011


Gernot Neppert wrote:
> When reading the documentation for SafeVarargs, there were 2 things
> that I found noteworthy:
>
> 1. the distinction between mandatory compiler errors and recommended
> warnings seems somehow arbitrary:
> Why is the use of  @SafeVarags on a method with reifiable
> variable-arity parameter not an error?
> Annotating such a method makes no more sense than annotating a method
> with fixed-arity!
>   

That is true, but is it is much easier for most Java programmers to tell 
whether or not a method is varargs then to tell whether or not the 
element type of the varargs parameters is reifiable. Quick, is Class<?> 
reifiable or not?

> 2. On the contrary, the sentence  'Future versions of the platform may
> mandate compiler errors for such unsafe operations.' smells fishy:
> this would result in code that is perfectly safe as verified by the
> programmer to become illegal in a future version. The reason is that
> the compiler cannot possibly determine whether a 'potentially unsafe'
> operation is, in fact, unsafe.
>   

For some definition of unsafe, there are classes of operations a 
compiler could determine were unsafe.  Conversely for some definition of 
safe.

> You need only have a look at java.util.Arrays.asList(T.. A) to see this:
>
> @SafeVarargs public static <T> List<T> asList(T... a) {
> 	return new ArrayList<T>(a);
>     }
>
> This would warrant a compiler warning since passing the variable-arity
> parameter to another method as an array is 'potentially unsafe'. It
> would be wrong, however, to reject the code 'in a future version'.
>   

Arrays.asList is anomalous in its use of varargs since it explicitly 
wants to alias the the argument to serve as the backing store of a new 
collection.  Typically, varargs methods just iterate over the elements 
of the array.


-Joe



More information about the coin-dev mailing list