Monday, August 29, 2011

One of new feature of JDK 7 is simplified varargs method invocation

As part of JDK 7, one of new feature is simplified varargs method invocation. With this change, when a user tries to invoke a varargs method with a non-reifiable varargs type, the compiler currently generates an unsafe operation warning.
But with this change, warning will be generate at method declaration instead of at method call. And this provides user with more specific location of warning.

Example :

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class VarArgTest {
// Warning location 1
static <T> void addToList(List<T> listObj, T... elements) {
for (T t : elements) {
// Warning location 2
static void faultyMethod(List<String>... l) {
Object[] objectArray = l; // Valid
objectArray[0] = Arrays.asList(new Integer(42));
String s = l[0].get(0); // ClassCastException thrown here

public static void main(String[] args) {
List<String> stringListA = new ArrayList<String>();
List<String> stringListB = new ArrayList<String>();

VarArgTest.addToList(stringListA, "Seven", "Eight", "Nine");
VarArgTest.addToList(stringListA, "Ten", "Eleven", "Twelve");
List<List<String>> listOfStringLists = new ArrayList<List<String>>();
// Warning location 3
VarArgTest.addToList(listOfStringLists, stringListA, stringListB);
// Warning location 4
VarArgTest.faultyMethod(Arrays.asList("Hello!"), Arrays.asList("World!"));


When we compile above program with earlier version of JDK i.e. prior to JDK 7, compiler will generate warning at warning location 3 and 4.
And if we compile above program with JDK 7, compiler will generate warning at warning location 1, 2, 3 and 4.

With this change in JDK 7, warning for varargs method invocation will generate warnings at method declaration which is more specific location for warnings. And advantage for this is safely and significantly reduces the total number of warnings reported to and suppressed by programmers.

Note : Please provide your views.

No comments:

Post a Comment