-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLambdaWrapExample.java
72 lines (58 loc) · 2.37 KB
/
LambdaWrapExample.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
64
65
66
67
68
69
70
71
72
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
// Only for testing
/**
* Created by paul dilley on 12/11/16.
* Allows you to tunnel up checked exceptions embedded within streams to a wrapper around the entire stream
*/
public class LambdaWrapExample {
public static void main(String args[]) {
String la = "pdsods";
// ORIGINAL: HOW YOU MIGHT HAVE TO HANDLE AN INLINE EXCEPTION WITHIN A STREAM
try {
Object fieldObjs = Arrays.stream(la.getClass().getFields())
.map(field -> {
try {
return field.get(la);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList());
System.out.println(fieldObjs);
} catch (RuntimeException e) {
e.printStackTrace();
}
// WRAPPER: HOW YOU CAN USE A WRAPPER TO BUBBLE UP THE EXCEPTIONS
try {
Object fieldObjs2 = LambdaWrap.withReturn(IllegalAccessException.class,
safe -> Arrays.stream(la.getClass().getFields())
.map(safe.function(field -> field.get(la)))
.collect(Collectors.toList()));
System.out.println(fieldObjs2);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
Object fieldObjs3 = LambdaWrap.withReturn(IllegalAccessException.class,
safe -> Arrays.stream(la.getClass().getFields())
.filter(safe.predicate(field -> field.get(la) == Object.class))
.collect(Collectors.toList()));
System.out.println(fieldObjs3);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
try {
LambdaWrap.withoutReturn(IllegalAccessException.class,
safe -> Arrays.asList(la.getClass().getFields()).forEach(
safe.consumer(field -> System.out.println(field.get(la)))
));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}