CKTIS / Java
@SafeVarargs — declaring safe varargs handling
`@SafeVarargs` is the author's assertion that a method or constructor handles its varargs parameter safely. It suppresses specific unchecked warnings at the declaration and call sites, but neither checks nor repairs type safety.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
@SafeVarargs
static <T> void inspect(T... values) { /* safe handling of values */ }SafeVarargs is an annotation in java.lang. A varargs parameter is handled as an array. When its element type is non-reifiable, such as List<String>, complete type information is unavailable at runtime. This creates a risk of heap pollution: values may not match their declared generic types.
@SafeVarargs suppresses the unchecked warning about such a declaration and parameterized array creation at call sites. Unlike @SuppressWarnings("unchecked") on a method declaration, it also affects calls to that method. It does not suppress every warning inside the method body.
In Java SE 21, it can annotate varargs constructors and varargs methods marked static, final, or private. Applying it to a declaration without varargs, or to a method that fails these conditions, is a compile-time error. For reifiable element types such as String, it is unnecessary and the compiler may warn.
This is the author's promise, not proof of safety. An unsafe write through an array alias can still cause ClassCastException. In the example, totalSize only reads the groups array, neither writing to it nor exposing it, which justifies the promise.
Examples
import java.util.List;
public class Main {
@SafeVarargs
static int totalSize(List<String>... groups) {
int total = 0;
for (List<String> group : groups) {
total += group.size();
}
return total;
}
public static void main(String[] args) {
System.out.println(totalSize(List.of("A", "B"), List.of("C")));
}
}Result
3
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.