Any use of CheckedFunction requires to use instanceof, but in most cases compiler would do it for us. Look at the little example:
java
class Test {
private static ResultSet throwsSQLException(Statement statement) throws SQLException {
return null;
}
private static String throwsIOException(File file) throws IOException {
return null;
}
private static ResultSet throwsMoreThanOneChecked(File file) throws SQLException, IOException {
return null;
}
}
If we want convert throwing SQLException function to unchecked we should write a lot meaningless code using Unchecked:
java
Unchecked.function(Test::throwsSQLException, t -> {
if (t instanceof SQLException) {
throw new UncheckedSQLException((SQLException) t);
}
// copy-paste for handling Error, RuntimeException and InterruptedException...
throw new RuntimeException(t);
});
but using function with generic exception:
java
public interface CheckedFunction<t r thr extends throwable> {
R apply(T t) throws THR;
static <t r thr extends throwable uce runtimeexception> Function<t r> checked(
CheckedFunction<t r thr> checked, Function<thr uce> exceptionHandler) {
return (t) -> {
try {
return checked.apply(t);
}
catch (RuntimeException | Error e) {
throw e;
}
catch (Throwable th) {
if (th instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
throw exceptionHandler.apply((THR) th);
}
};
}
}
</thr></t></t></t></t>
we can optimize two of three cases. If methods throws single checked exception compiler will infer type of this exception so we can just write
java
CheckedFunction.checked(Test::throwsSQLException, UncheckedSQLException::new);
CheckedFunction.checked(Test::throwsIOException, UncheckedIOException::new);
When function throws more than one checked exception compilers can't put two exceptions and requires Throwable to be handled:
java
CheckedFunction.checked(Test::throwsMoreThanOneChecked, RuntimeException::new);
Also using transforming function protects us from checking than exception was thown and user actually understands what we exactly want.
该提问来源于开源项目:jOOQ/jOOL