【发布时间】:2023-03-09 16:31:02
【问题描述】:
我正在尝试包装引发检查异常的方法。我正在按照以下网址中的步骤操作:https://www.rainerhahnekamp.com/en/ignoring-exceptions-in-java/
有趣的是,当我这样编写代码时:
IntStream.range(1, locales.length)
.mapToObj(i -> locales[i].toString())
.forEach(wrap(this::testLocale));
它工作正常,但是当我这样写时:
IntStream.range(1, locales.length)
.mapToObj(i -> locales[i].toString())
.forEach(s -> wrap(testLocale(s)));
Intellij 抱怨“未处理的异常:java.lang.Exception”
这里的 testLocale 看起来像这样:
void testLocale(String s) throws Exception
wrap 函数如下所示:
public static <T> Consumer<T> wrap(WrapConsumer<T> wrapper) {
return t -> {
try {
wrapper.accept(t);
} catch(Exception exception) {
throw new RuntimeException(exception);
}
};
}
WrapConsumer 是一个带有 Consumer 签名的函数接口:
@FunctionalInterface
public interface WrapConsumer<T> {
void accept(T t) throws Exception;
}
我正在努力理解为什么 Intellij 会根据我编写 lambda 的方式抱怨
【问题讨论】:
-
.forEach(wrap(s -> testLocale(s)))。您必须包装消费者,而不是方法调用。进一步注意,您可以使用Arrays.stream(locales, 1, locales.length) .map(Object::toString) .forEach(wrap(this::testLocale))。
标签: java exception lambda java-8