如果抛出异常,是否有更优雅的过滤方法?
我的意思是,目前我的代码看起来是:
stream.filter(item -> {
try {
validator.with(reference)
.hasAccess(this.authzManager)
.isOwner();
} catch (EspaiDocFault | DataAccessException e) {
return false;
}
return true;
}
)我要做的是,如果抛出异常,则必须过滤当前项流。
我在找任何现有的util类或者类似的..。
发布于 2018-12-13 15:34:09
我在许多变体中看到的一种非常常见的方法是编写自己的功能接口,它将允许抛出一个检查过的异常(1),并使该解决方案适应内置接口(2)。
/**
* An EPredicate is a Predicate that allows a checked exception to be thrown.
*
* @param <T> the type of the input to the predicate
* @param <E> the allowed exception
*/
@FunctionalInterface
public interface EPredicate<T, E extends Exception> {
/**
* (1) the method permits a checked exception
*/
boolean test(T t) throws E;
/**
* (2) the method adapts an EPredicate to a Predicate.
*/
static <T, E extends Exception> Predicate<T> unwrap(EPredicate<T, E> predicate) {
return t -> {
try {
return predicate.test(t);
} catch (Exception e) {
return false;
}
};
}
}一个例子看上去相当优雅:
.stream()
.filter(EPredicate.<ItemType, Exception>unwrap(item -> validator.[...].isOwner()))哪里,
ItemType是item的类型;Exception是EspaiDocFault和DataAccessException的共同父级。.stream()
.filter(EPredicate.unwrap(item -> validator.[...].isOwner()))发布于 2018-12-13 15:17:40
瓦沃尔库有一个Try类,它可以做您想做的事情:
stream.filter(item -> Try.of(() -> validator.with(reference)
.hasAccess(this.authzManager)
.isOwner()).getOrElse(false))编辑:如果您真的想知道异常是否被抛出,Vavr也可以这样做:
stream.filter(item -> Try.of([...]).isSuccess())或者,将整个过程包装在一个方法中:
stream.filter(this::getMyBooleanWithinMyTry)https://stackoverflow.com/questions/53764580
复制相似问题