抛出java类型异常的方法_Java Streams:抛出异常的优雅方法
我在許多變體中看到的一種非常常見的方法是編寫自己的功能接口,該功能接口將引發(fā)拋出已檢查的異常(1),并使該解決方案適應(yīng)內(nèi)置接口(2).
/**
* An EPredicate is a Predicate that allows a checked exception to be thrown.
*
* @param the type of the input to the predicate
* @param the allowed exception
*/
@FunctionalInterface
public interface EPredicate {
/**
* (1) the method permits a checked exception
*/
boolean test(T t) throws E;
/**
* (2) the method adapts an EPredicate to a Predicate.
*/
static Predicate unwrap(EPredicate predicate) {
return t -> {
try {
return predicate.test(t);
} catch (Exception e) {
return false;
}
};
}
}
一個(gè)例子看起來很優(yōu)雅:
.stream()
.filter(EPredicate.unwrap(item -> validator.[...].isOwner()))
哪里,
> ItemType是項(xiàng)目的類型;
>異常是EspaiDocFault和DataAccessException的共同父代.
.stream()
.filter(EPredicate.unwrap(item -> validator.[...].isOwner()))
總結(jié)
以上是生活随笔為你收集整理的抛出java类型异常的方法_Java Streams:抛出异常的优雅方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java格式错误什么意思_java.io
- 下一篇: java 字段验证_Selenium-G