-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathHelpfulNPEMessages.java
63 lines (53 loc) · 1.2 KB
/
HelpfulNPEMessages.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
61
62
63
import static java.util.stream.Collectors.toList;
import java.util.stream.IntStream;
/**
* To run: `java -XX:+ShowCodeDetailsInExceptionMessages HelpfulNPEMessages.java`
*/
public class HelpfulNPEMessages {
public static void main(String[] args) {
simpleObjectAccess();
insideStreams();
}
private static void simpleObjectAccess() {
System.out.println("=== Simple Object Attribute Access ===");
try {
var thing = new Thing(11);
System.out.println("Value " + thing.weight.value);
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
private static void insideStreams() {
System.out.println("%n=== Attribute Access Inside Streams ===");
try {
IntStream.of(2, 4, 6, 8, 9)
.mapToObj(Thing::new)
.map(thing -> thing.weight.value)
.forEach(v -> System.out.println("Val " + v));
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
class Thing {
Weight weight;
Thing(int weight) {
if (weight % 2 == 0) {
this.weight = new Weight(weight);
}
}
public Weight getWeight() {
return weight;
}
}
class Weight {
Integer value;
Weight(int value) {
if (value % 2 == 0) {
this.value = value;
}
}
public int getValue() {
return value;
}
}