Java : @SafeVarargs (annotation) with Examples
SafeVarargs (Java SE 20 & JDK 20) with Examples.
You will find code examples on most SafeVarargs methods.
Summary
An example with unchecked warnings :
public class Foo<T> {
public void m(T... args) {
System.out.println(Arrays.toString(args));
}
}
//> javac -Xlint:unchecked Foo.java
//Foo.java:6: warning: [unchecked] Possible heap pollution from parameterized vararg type T
// public void m(T... args) {
// ^
// where T is a type-variable:
// T extends Object declared in class Foo
//1 warning
An example with @SafeVarargs :
public class Foo<T> {
@SafeVarargs
public final void m(T... args) {
System.out.println(Arrays.toString(args));
}
}
> javac -Xlint:unchecked Foo.java
<No errors and warnings>
An example with unsafe operations on varargs parameter :
public class Bar {
public static List<String>[] m(List<String>... args) {
if (0 < args.length) {
Object[] objects = args;
objects[args.length - 1] = List.of(123);
}
return args;
}
}
List<String>[] listArray = Bar.m(
List.of("aaa"),
List.of("bbb"),
List.of("ccc")
);
try {
System.out.println("-- listArray --");
for (final var list : listArray) {
if (!list.isEmpty()) {
String str = list.get(0);
System.out.println(str);
}
}
} catch (ClassCastException e) {
System.out.println("ClassCastException!");
}
// Result
// ↓
//-- listArray --
//aaa
//bbb
//ClassCastException!
Related posts
- API Examples