@SafeVarargs annotation for private methods in Java 9?

JavaObject Oriented ProgrammingProgramming

The @SafeVarargs annotation was introduced in Java 7. This annotation applies to both final and static methods or constructors that take varargs parameters. This annotation used to make sure that a method does not perform unsafe operations on its varargs parameters. Since Java 9, @SafeVarargs annotation also applies to private instance methods.

Syntax

@SafeVarargs
private void methodName(...) {
   // some statements
}

Example

import java.util.ArrayList;
import java.util.List;
public class SafevarargsTest {
   @SafeVarargs     // Apply @SafeVarargs to private methods
   private void display(List<String>... names) {
      for(List<String> name : names) {
         System.out.println(name);
      }
   }
   public static void main(String args[]) {
      SafevarargsTest test = new SafevarargsTest();
      List<String> list = new ArrayList<String>();
      list.add("TutorialsPoint");
      list.add("Tutorix");
      test.display(list);
   }
}

Output

[TutorialsPoint, Tutorix]
raja
Published on 13-Feb-2020 13:38:49
Advertisements