Learnitweb

Java 9 SafeVarargs Annotation Enhancements

1. Introduction

In this article, we’ll discuss the SafeVarargs annotation enhancement in Java 9. Before discussing that, we’ll discuss briefly about the @SafeVarargs annotation.

From Java 9 onwards, you can also use @SafeVarargs annotation for private instance methods also.

2. @SafeVarargs Annotation

If you use var-arg methods with generic type then at runtime if one type variable points to another type value, then this will result in ClasssCastException. This problem is called Heap pollution. If your code may lead to Heap pollution, the compiler will generate warnings.

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

public class Test {

	public static void main(String[] args) {
		List<String> l1 = Arrays.asList("A", "B");
		List<String> l2 = Arrays.asList("C", "D");
		someMethod(l1, l2);
	}

	public static void someMethod(List<String>... l)// argument will become List<String>[]
	{
		Object[] a = l; // assign List[] to Object[]
		a[0] = Arrays.asList(15, 30);
		String name = (String) l[0].get(0);// String type pointing to Integer type
		System.out.println(name);
	}
}

If you compile the code, you’ll see the warning like the following:

>javac -Xlint:unchecked Test.java

Test.java:11: warning: [unchecked] unchecked generic array creation for varargs parameter of type List<String>[]
                m1(l1, l2);
                  ^
Test.java:14: warning: [unchecked] Possible heap pollution from parameterized vararg type List<String>
        public static void m1(List<String>... l)// argument will become List<String>[]

Not all var-arg methods cause Heap pollution. If you are sure that your method won’t cause Heap pollution, then you can suppress compiler warnings with @SafeVarargs annotation.

	@SafeVarargs
	public static void someMethod(List<String>... l) {
		for (List<String> l1 : l) {
			System.out.println(l1);
		}
	}

3. Java 9 enhancement to @SafeVarargs annotation

@SafeVarargs annotation was introduced in Java 7. Before Java 9, this annotation is applicable only for static methods,final methods and constructors.

But from Java 9 onwards, you can also use @SafeVarargs annotation for private instance methods also.

Following is a valid code in Java 9.

@SafeVarargs //valid in Java 9 but not in Java 8
private void m3(List<String>... l)
{
	// some method body
} 

4. Conclusion

In this article, we discussed the SafeVarargs annotation and the Java 9 SafeVarargs annotation enhancements. Hope this article was helpful.