-
Notifications
You must be signed in to change notification settings - Fork 81
/
SafeVarargs.java
60 lines (45 loc) · 1.28 KB
/
SafeVarargs.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package dev.nipafx.demo.java9.lang.safe_varargs;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import static java.util.Arrays.stream;
class SafeVarargs {
public static void main(String[] args) {
String[] bar = new UnSafeVarargs().replaceTwoNulls(", ", "hello", null);
Arrays.stream(bar).forEach(System.out::print);
System.out.println();
}
class InJava8 {
// @java.lang.SafeVarargs
// With the annotation, it would not compile
// because the method is private and non-final.
// Without the annotation, we get a pesky warning.
private <T> Optional<T> firstNonNull(T... args) {
return stream(args)
.filter(Objects::nonNull)
.findFirst();
}
}
class InJava9 {
@java.lang.SafeVarargs
// here we go with Java 9
private final <T> Optional<T> firstNonNull(T... args) {
return stream(args)
.filter(Objects::nonNull)
.findFirst();
}
}
public static class UnSafeVarargs {
// calling this results in a runtime exception
private <T> T[] replaceTwoNulls(T value, T first, T second) {
return replaceAllNulls(value, first, second);
}
private <T> T[] replaceAllNulls(T value, T... args) {
for (int i = 0; i < args.length; i++) {
if (args[i] == null)
args[i] = value;
}
return args;
}
}
}