Safe Varargs
Gernot Neppert
mcnepp02 at googlemail.com
Tue Jan 25 06:16:56 PST 2011
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!
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.
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'.
2011/1/25 Joe Darcy <joe.darcy at oracle.com>:
>> In addition to the usage restrictions imposed by its @Target
>> meta-annotation, compilers are required to implement additional usage
>> restrictions on this annotation type; it is a compile-time error if a
>> method or constructor declaration is annotated with a @SafeVarargs
>> annotation, and either:
>>
>> * the declaration is a fixed-arity method or constructor
>> * the declaration is a variable-arity method that is neither
>> static nor final.
>>
>> Compilers are encouraged to issue warnings when this annotation type
>> is applied to a method or constructor declaration where:
>>
>> * The variable-arity parameter has a reifiable element type,
>> which includes primitive types, Object, and String. (The unchecked
>> warnings this annotation type suppresses already do not occur for a
>> reifiable element type.)
>> * The body of the method or constructor declaration performs
>> potentially unsafe operations, such as an assignment to an element of
>> the variable-arity parameter's array that generates an unchecked warning.
>>
>> Future versions of the platform may mandate compiler errors
>> for such unsafe operations.
>>
More information about the coin-dev
mailing list