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