|
| 1 | +package com.winterbe.java8.samples.misc; |
| 2 | + |
| 3 | +import java.util.function.Consumer; |
| 4 | +import java.util.function.Function; |
| 5 | +import java.util.function.Predicate; |
| 6 | + |
| 7 | +/** |
| 8 | + * Utilities for hassle-free usage of lambda expressions who throw checked exceptions. |
| 9 | + * |
| 10 | + * @author Benjamin Winterberg |
| 11 | + */ |
| 12 | +public final class CheckedFunctions { |
| 13 | + |
| 14 | + @FunctionalInterface |
| 15 | + public interface CheckedConsumer<T> { |
| 16 | + void accept(T input) throws Exception; |
| 17 | + } |
| 18 | + |
| 19 | + @FunctionalInterface |
| 20 | + public interface CheckedPredicate<T> { |
| 21 | + boolean test(T input) throws Exception; |
| 22 | + } |
| 23 | + |
| 24 | + @FunctionalInterface |
| 25 | + public interface CheckedFunction<F, T> { |
| 26 | + T apply(F input) throws Exception; |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * Return a function which rethrows possible checked exceptions as runtime exception. |
| 31 | + * |
| 32 | + * @param function |
| 33 | + * @param <F> |
| 34 | + * @param <T> |
| 35 | + * @return |
| 36 | + */ |
| 37 | + public static <F, T> Function<F, T> function(CheckedFunction<F, T> function) { |
| 38 | + return input -> { |
| 39 | + try { |
| 40 | + return function.apply(input); |
| 41 | + } |
| 42 | + catch (Exception e) { |
| 43 | + if (e instanceof RuntimeException) { |
| 44 | + throw (RuntimeException) e; |
| 45 | + } |
| 46 | + throw new RuntimeException(e); |
| 47 | + } |
| 48 | + }; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * Return a predicate which rethrows possible checked exceptions as runtime exception. |
| 53 | + * |
| 54 | + * @param predicate |
| 55 | + * @param <T> |
| 56 | + * @return |
| 57 | + */ |
| 58 | + public static <T> Predicate<T> predicate(CheckedPredicate<T> predicate) { |
| 59 | + return input -> { |
| 60 | + try { |
| 61 | + return predicate.test(input); |
| 62 | + } |
| 63 | + catch (Exception e) { |
| 64 | + if (e instanceof RuntimeException) { |
| 65 | + throw (RuntimeException) e; |
| 66 | + } |
| 67 | + throw new RuntimeException(e); |
| 68 | + } |
| 69 | + }; |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Return a consumer which rethrows possible checked exceptions as runtime exception. |
| 74 | + * |
| 75 | + * @param consumer |
| 76 | + * @param <T> |
| 77 | + * @return |
| 78 | + */ |
| 79 | + public static <T> Consumer<T> consumer(CheckedConsumer<T> consumer) { |
| 80 | + return input -> { |
| 81 | + try { |
| 82 | + consumer.accept(input); |
| 83 | + } |
| 84 | + catch (Exception e) { |
| 85 | + if (e instanceof RuntimeException) { |
| 86 | + throw (RuntimeException) e; |
| 87 | + } |
| 88 | + throw new RuntimeException(e); |
| 89 | + } |
| 90 | + }; |
| 91 | + } |
| 92 | +} |
0 commit comments