小编典典
该LambdaExceptionUtil帮助程序类使你可以在Java流中使用任何已检查的异常,如下所示:
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(rethrowFunction(Class::forName))
.collect(Collectors.toList());
注意Class::forName抛出异常ClassNotFoundException,已被选中。流本身也会抛出ClassNotFoundException,而不是一些包装未检查的异常。
public final class LambdaExceptionUtil {
@FunctionalInterface
public interface Consumer_WithExceptions {
void accept(T t) throws E;
}
@FunctionalInterface
public interface BiConsumer_WithExceptions {
void accept(T t, U u) throws E;
}
@FunctionalInterface
public interface Function_WithExceptions {
R apply(T t) throws E;
}
@FunctionalInterface
public interface Supplier_WithExceptions {
T get() throws E;
}
@FunctionalInterface
public interface Runnable_WithExceptions {
void run() throws E;
}
/** .forEach(rethrowConsumer(name -> System.out.println(Class.forName(name)))); or .forEach(rethrowConsumer(ClassNameUtil::println)); */
public static Consumer rethrowConsumer(Consumer_WithExceptions consumer) throws E {
return t -> {
try { consumer.accept(t); }
catch (Exception exception) { throwAsUnchecked(exception); }
};
}
public static BiConsumer rethrowBiConsumer(BiConsumer_WithExceptions biConsumer) throws E {
return (t, u) -> {
try { biConsumer.accept(t, u); }
catch (Exception exception) { throwAsUnchecked(exception); }
};
}
/** .map(rethrowFunction(name -> Class.forName(name))) or .map(rethrowFunction(Class::forName)) */
public static Function rethrowFunction(Function_WithExceptions function) throws E {
return t -> {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
/** rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))), */
public static Supplier rethrowSupplier(Supplier_WithExceptions function) throws E {
return () -> {
try { return function.get(); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
};
}
/** uncheck(() -> Class.forName("xxx")); */
public static void uncheck(Runnable_WithExceptions t)
{
try { t.run(); }
catch (Exception exception) { throwAsUnchecked(exception); }
}
/** uncheck(() -> Class.forName("xxx")); */
public static R uncheck(Supplier_WithExceptions supplier)
{
try { return supplier.get(); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
}
/** uncheck(Class::forName, "xxx"); */
public static R uncheck(Function_WithExceptions function, T t) {
try { return function.apply(t); }
catch (Exception exception) { throwAsUnchecked(exception); return null; }
}
@SuppressWarnings ("unchecked")
private static void throwAsUnchecked(Exception exception) throws E { throw (E)exception; }
}
有关如何使用它的许多其他示例(静态导入后LambdaExceptionUtil):
@Test
public void test_Consumer_with_checked_exceptions() throws IllegalAccessException {
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.forEach(rethrowConsumer(className -> System.out.println(Class.forName(className))));
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.forEach(rethrowConsumer(System.out::println));
}
@Test
public void test_Function_with_checked_exceptions() throws ClassNotFoundException {
List classes1
= Stream.of("Object", "Integer", "String")
.map(rethrowFunction(className -> Class.forName("java.lang." + className)))
.collect(Collectors.toList());
List classes2
= Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
.map(rethrowFunction(Class::forName))
.collect(Collectors.toList());
}
@Test
public void test_Supplier_with_checked_exceptions() throws ClassNotFoundException {
Collector.of(
rethrowSupplier(() -> new StringJoiner(new String(new byte[]{77, 97, 114, 107}, "UTF-8"))),
StringJoiner::add, StringJoiner::merge, StringJoiner::toString);
}
@Test
public void test_uncheck_exception_thrown_by_method() {
Class clazz1 = uncheck(() -> Class.forName("java.lang.String"));
Class clazz2 = uncheck(Class::forName, "java.lang.String");
}
@Test (expected = ClassNotFoundException.class)
public void test_if_correct_exception_is_still_thrown_by_method() {
Class clazz3 = uncheck(Class::forName, "INVALID");
}
注意1:可以使用上述类的rethrow方法LambdaExceptionUtil而不必担心,在任何情况下都可以使用。非常感谢帮助解决最后一个问题的用户@PaoloC:现在,编译器将要求你添加throw子句,一切都好像你可以在Java 8流上本地抛出检查异常一样。
注意2:uncheck上述LambdaExceptionUtil类的方法是奖励方法,如果你不想使用它们,可以将其安全地从类中删除。如果你确实使用过它们,请谨慎操作,而不要先了解以下用例,优点/缺点和限制:
• uncheck如果要调用一个从字面上永远不会引发其声明的异常的方法,则可以使用这些方法。例如:new String(byteArr,“ UTF-8”)引发UnsupportedEncodingException,但是Java规范保证UTF-8始终存在。在这里,throws声明是个麻烦事,欢迎使用最小的样板来使它静音的任何解决方案:String text = uncheck(() -> new String(byteArr, "UTF-8"));
• uncheck如果要实现一个严格的接口,而该接口没有添加throws声明的选项,但是抛出异常是完全适当的,则可以使用这些方法。包装异常只是为了获得抛出异常的特权,会导致产生带有虚假异常的堆栈跟踪,这些异常不会提供有关实际出了什么问题的信息。一个很好的例子是Runnable.run(),它不会引发任何检查的异常。
•无论如何,如果你决定使用这些uncheck方法,请注意在没有throws子句的情况下抛出CHECKED异常的两种后果:1)调用代码将无法按名称捕获(如果尝试,则编译器会说:永远不会在相应的try语句的主体中引发异常)。它会冒泡,并且可能会被某些“ catch Exception”或“ catch Throwable”捕获在主程序循环中,这可能还是你想要的。2)它违反了最少惊讶的原则:它将不再足以RuntimeException确保能够捕获所有可能的异常。因此,我认为这不应在框架代码中完成,而应在完全控制的业务代码中完成。
2020-03-02