Return to site

@SafeVarargs Annotation

Like @SupressWarnings but for varargs parameters

· java

Define

@SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.

Cause

Before Java 9 versions, if vararg methods are used with generics, then there is a warning message. Even though not all methods create heap pollution, compiler shows warning for all vararg methods used with generics. That's the reason @SafeVarargs concept was added to Java 9 version to avoid these warnings

Conclusion

So use @SafeVarargs annotation on final or static methods and constructors. @SafeVarargs is like @SupressWarnings in that it allows us to declare that a particular compiler warning is a false positive.

Snippet