Java Reference
In-Depth Information
Varargs Methods and Heap Pollution Warnings
Java 7 has improved warnings for a varargs method with a non-reifiable type parameter. Java implements the varargs
parameter of a varargs method by converting the varargs parameter into an array. If a varargs method uses a generic
type varargs parameter, Java cannot guarantee the type-safety. A non-reifiable generic type varargs parameter may
possibly lead to heap pollution.
Consider the following snippet of code that declares a process() method with a parameterized type parameter
nums . The comments in the method's body indicate the heap pollution and other types of problems.
// A unchecked and varargs warnings in Java 7
public static void process(Wrapper<Long>…nums) {
Object[] obj = nums; // Heap pollution
obj[0] = new Wrapper<String>("Hello"); // Array corruption
Long lv = nums[0].get(); // A ClassCastException
// Other code goes here
}
When the process() method is compiled, the compiler removes the type information <Long> from its
parameterized type parameter and changes its signature to process(Wrapper[] nums) . When you compile the above
declaration of the process() method, you will get the following unchecked warning:
warning: [unchecked] Possible heap pollution from parameterized vararg type Wrapper<Long>
public static void process(Wrapper<Long>...nums) {
^
1 warning
Consider the following snippet of code that calls the process() method:
Wrapper<Long> v1 = new Wrapper<Long>(10L);
Wrapper<Long> v2 = new Wrapper<Long>(11L);
process(v1, v2); // An unchecked warning in Java 5, 6, 7
When the above snippet of code is compiled, it generates the following compiler unchecked warning:
warning: [unchecked] unchecked generic array creation for varargs parameter of type Wrapper<Long>[]
process(v1, v2);
^
1 warning
Until Java 6, the compiler generated a warning at the location where the varargs method with a non-reifiable
generic varargs type parameter was called. The possible heap pollution problem may exist inside the method. Java 7
has improved the warning by generating a warning at the method declaration as well as at the location of the method
call. If you create such a method, it is your responsibility to ensure that heap pollution does not occur inside your
method's body.
If you create a varargs method with a non-reifiable type parameter, you can suppress the unchecked warnings at
the location of the method's declaration as well as the method's call by using @java.lang.SafeVarargs annotation. By
using the @SafeVarargs annotation, you are asserting that your varargs method with non-reifiable type parameter is
safe to use. The following snippet of code uses @SafeVarargs annotation with the process() method:
@java.lang.SafeVarargs
public static void process(Wrapper<Long>...nums) {
Object[] obj = nums; // Heap pollution
 
Search WWH ::




Custom Search