Java9 Features – Part 4 | Safevarargs

Safevarargs and @Deprecated are living under the shadows of Jshell, Interface Enhancement, Collections, but they prove to be useful at times.

1) Safevarargs

Until Java 8, @SafeVarargs could only be applied to static methods, final methods and constructors. None of them can be overridden.

This list was missing one more candidate that could also not be overridden and that was a private method. And Java 9 has made it possible to add @SafeVarargs to the private method.

Here is a valid example in Java 9 but in Java 8 it throws compile error @SafeVarargs annotation cannot be applied to non-final instance method iAmSafeVaragrsMethod

 @SafeVarargs
      private void iAmSafeVaragrsMethod(String... varargs)
      {
         for (String each: varagrgs) {
            System.out.println(each);
         }
      }





ALSO READ :- Java9 Features Part 2 | Collections | JavaDocs
ALSO READ :- Java9 Features Part 3 | Multi Release Jar Feature


Why @ Safevarargs is required?

Scenario I – Prior to Java 7, usage of code without @SafeVarargs

public class Class6{

public static void main(String[] args) {
java6();
}

private static void java6() {
List< Integer > listOfIntegers = new ArrayList< >();
listOfIntegers.add(1);
listOfIntegers.add(2);
listOfIntegers.add(3);
listOfIntegers.add(4);

display(listOfIntegers);
}

// Throws a warning for Type safety: 
//Potential heap pollution via varargs parameter lists
private static < T > void display(T... lists) {
for(T element : lists) {
System.out.println(element);
}
}
}

 

Scenario II – After Java 7, usage of code with @SafeVarargs

public class A{

public static void main(String[] args) {
java7();
}

private static void java7() {

List< Integer > listOfIntegers = new ArrayList< >();
listOfIntegers.add(1);
listOfIntegers.add(2);
listOfIntegers.add(3);
listOfIntegers.add(4);

display(listOfIntegers);
}

// With usage of @SafeVarargs the Type Safety warning has been supressed
@SafeVarargs
private static < T > void displaywithSafeVarargs(T... lists) {
for(T element : lists) {
System.out.println(element);
}
}
}

ALSO READ:-






Leave a Reply

Your email address will not be published. Required fields are marked *