假设您有一个公开下一个接口的第 3 方库。
interface Mapper {
String doMap(String input) throws CheckedException;
}
class CheckedException extends Exception {
}
我知道检查异常在 Java 中通常是一种不好的做法,但是这段代码来自第三方,我无法修改它。
我想将 Mapper 接口的实现与 Java8 流 API 结合使用。考虑下面的示例实现。
class MapperImpl implements Mapper {
public String doMap(String input) throws CheckedException {
return input;
}
}
例如,现在,我想将映射器应用于字符串集合。
public static void main(String[] args) {
List<String> strings = Arrays.asList("foo", "bar", "baz");
Mapper mapper = new MapperImpl();
List<String> mappedStrings = strings
.stream()
.map(mapper::doMap)
.collect(Collectors.toList());
}
代码无法编译,因为 Function 不知道如何处理由 doMap 声明的 CheckedException。我想出了两种可能的解决方案。
解决方案#1 - 包装调用
.map(value -> {
try {
return mapper.doMap(value);
} catch (CheckedException e) {
throw new UncheckedException();
}
})
解决方案#2 - 编写一个实用方法
public static final String uncheck (Mapper mapper, String input){
try {
return mapper.doMap(input);
} catch (CheckedException e){
throw new UncheckedException();
}
}
然后我可以使用
.map(value -> Utils.uncheck(mapper, value))
在您看来,在 Java8 流的上下文中(以及在更广泛的 lambda 表达式上下文中)处理已检查异常的最佳方法是什么?
谢谢!
泛舟湖上清波郎朗
相关分类