创建一个自定义返回类型,该类型将传播检查的异常。这是创建一个镜像现有功能接口的新接口的替代方法,只需稍微修改功能接口的方法上的“抛出异常”。
定义
CheckedValueSupplier
public static interface CheckedValueSupplier<V> {
public V get () throws Exception;
}
检查值
public class CheckedValue<V> {
private final V v;
private final Optional<Exception> opt;
public Value (V v) {
this.v = v;
}
public Value (Exception e) {
this.opt = Optional.of(e);
}
public V get () throws Exception {
if (opt.isPresent()) {
throw opt.get();
}
return v;
}
public Optional<Exception> getException () {
return opt;
}
public static <T> CheckedValue<T> returns (T t) {
return new CheckedValue<T>(t);
}
public static <T> CheckedValue<T> rethrows (Exception e) {
return new CheckedValue<T>(e);
}
public static <V> CheckedValue<V> from (CheckedValueSupplier<V> sup) {
try {
return CheckedValue.returns(sup.get());
} catch (Exception e) {
return Result.rethrows(e);
}
}
public static <V> CheckedValue<V> escalates (CheckedValueSupplier<V> sup) {
try {
return CheckedValue.returns(sup.get());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
用法
// Don't use this pattern with FileReader, it's meant to be an
// example. FileReader is a Closeable resource and as such should
// be managed in a try-with-resources block or in another safe
// manner that will make sure it is closed properly.
// This will not compile as the FileReader constructor throws
// an IOException.
Function<String, FileReader> sToFr =
(fn) -> new FileReader(Paths.get(fn).toFile());
// Alternative, this will compile.
Function<String, CheckedValue<FileReader>> sToFr = (fn) -> {
return CheckedValue.from (
() -> new FileReader(Paths.get("/home/" + f).toFile()));
};
// Single record usage
// The call to get() will propagate the checked exception if it exists.
FileReader readMe = pToFr.apply("/home/README").get();
// List of records usage
List<String> paths = ...; //a list of paths to files
Collection<CheckedValue<FileReader>> frs =
paths.stream().map(pToFr).collect(Collectors.toList());
// Find out if creation of a file reader failed.
boolean anyErrors = frs.stream()
.filter(f -> f.getException().isPresent())
.findAny().isPresent();
发生了什么事?
创建一个引发检查异常的单一功能接口 (CheckedValueSupplier)。这将是唯一允许检查异常的功能接口。所有其他功能接口都将利用CheckedValueSupplier 包装任何引发检查异常的代码。
CheckedValue 类将保存执行任何引发检查异常的逻辑的结果。这可以防止已检查异常的传播,直到代码尝试访问 CheckedValue 的实例所包含的值。
这种方法的问题。
- 我们现在抛出“异常”,有效地隐藏了最初抛出的特定类型。
- 在调用
CheckedValue#get() 之前,我们不知道发生了异常。
消费者等
某些功能接口(例如Consumer)必须以不同的方式处理,因为它们不提供返回值。
代替消费者的功能
一种方法是使用函数而不是消费者,这适用于处理流。
List<String> lst = Lists.newArrayList();
// won't compile
lst.stream().forEach(e -> throwyMethod(e));
// compiles
lst.stream()
.map(e -> CheckedValueSupplier.from(
() -> {throwyMethod(e); return e;}))
.filter(v -> v.getException().isPresent()); //this example may not actually run due to lazy stream behavior
升级
或者,您可以随时升级到RuntimeException。还有其他答案涵盖了从 Consumer 中升级检查的异常。
不要食用。
完全避免使用函数式接口并使用老式的 for 循环。