|
|
|
|
|
by BrandonM
4277 days ago
|
|
We currently use the following pattern: interface ConsumerE<T, E extends Exception> {
void accept(T t) throws E;
}
This actually works! The type inference is good enough to figure out the actual type of E.Note that Java 8 also includes specialized wrappers like RuntimeIOException. So it might be nice to extend your example: static <T, E extends Exception> Consumer<T> wrapped(
Function<? super E, RuntimeException> wrapper,
ConsumerE<T, E> consumer) {
return (t) -> {
try {
consumer.accept(t);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw wrapper.apply((E) e);
}
};
}
Used as follows: Consumer<String> printer = wrapped(RuntimeIOException::new, writer::write);
|
|