lambda受检异常

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
public class Try {
public Try() {
}

public static <T, R> Function<T, R> of(Try.UncheckedFunction<T, R> mapper) {
Objects.requireNonNull(mapper);
return (t) -> {
try {
return mapper.apply(t);
} catch (Exception var3) {
throw Exceptions.unchecked(var3);
}
};
}

public static <T> Consumer<T> of(Try.UncheckedConsumer<T> mapper) {
Objects.requireNonNull(mapper);
return (t) -> {
try {
mapper.accept(t);
} catch (Exception var3) {
throw Exceptions.unchecked(var3);
}
};
}

public static <T> Supplier<T> of(Try.UncheckedSupplier<T> mapper) {
Objects.requireNonNull(mapper);
return () -> {
try {
return mapper.get();
} catch (Exception var2) {
throw Exceptions.unchecked(var2);
}
};
}

@FunctionalInterface
public interface UncheckedSupplier<T> {
@Nullable
T get() throws Exception;
}

@FunctionalInterface
public interface UncheckedConsumer<T> {
@Nullable
void accept(@Nullable T t) throws Exception;
}

@FunctionalInterface
public interface UncheckedFunction<T, R> {
@Nullable
R apply(@Nullable T t) throws Exception;
}
}

Function 用法

1
2
3
4
5
User apply = Try.of((String userStr) -> {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(userStr, User.class);
}).apply(s3);
System.out.println(apply);

Supplier 用法

1
2
3
4
5
User aaa = Try.of(() -> {
System.out.println("走if");
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(s3, User.class);
}).get();

Consumer用法

1
2
3
4
5
6
7
String s3 = "{\"name\":221, \"id\":1}";

Try.of((String str) -> {
ObjectMapper objectMapper = new ObjectMapper();
User user = objectMapper.readValue(str, User.class);
System.out.println(user);
}).accept(s3);

lambda中使用

1
2
3
4
5
User user2 = Optional.ofNullable(s3)
.map(Try.of((String userStr) -> {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(userStr, User.class);
})).orElse(null);

predicate

1
2
3
4
5
objects.stream().filter(Try.predicate(user -> {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.readValue(s3, User.class);
return user.getId().equals(1);
})).collect(Collectors.toList());
1
2
3
4
5
6
7
8
9
10
11
public static <T> Predicate<T> predicate(Try.UncheckedPredicate<T> mapper) {
Objects.requireNonNull(mapper);
return (t) -> {
try {
return mapper.test(t);
} catch (Exception var3) {
throw Exceptions.unchecked(var3);
}
};
}

1
2
3
4
5
@FunctionalInterface
public interface UncheckedPredicate<T> {
@Nullable
boolean test(T t) throws Exception;
}