Java函數(shù)式斷言接口Predicate的一個小小實踐
最近在搞Excel導(dǎo)入,數(shù)據(jù)校驗是少不了的,但是不同的數(shù)據(jù)字段有不同的校驗策略,五花八門的,甚至不確定,沒有辦法使用JSR303。所以就搞一個校驗策略工具,把校驗策略抽象出來。這里嘗試了Java  8 提供的一個斷言函數(shù)接口java.util.function.Predicate
Predicate接口
Predicate的應(yīng)用
先來看看效果:
- boolean validated = new Validator<String>()
 - .with(s -> s.length() > 5)
 - .with(s -> s.startsWith("felord"))
 - .with(s -> s.endsWith("cn"))
 - .with(s -> s.contains("."))
 - .validate("felord.cn");
 
我拿校驗字符串為例子,通過一系列的Predicate
- public class UserServiceImpl implements UserService {
 - @Override
 - public boolean checkUserByName(String name) {
 - return false;
 - }
 - }
 
對應(yīng)的校驗可以改為:
- UserServiceImpl userService = new UserServiceImpl();
 - boolean validated = new Validator<String>()
 - .with(s -> s.length() > 5)
 - .with(s -> s.startsWith("felord"))
 - .with(userService::checkUserByName)
 - .validate("felord.cn");
 
好奇的同學(xué)該想知道是怎么實現(xiàn)的,Validator
- import java.util.function.Predicate;
 - public class Validator<T> {
 - /**
 - * 初始化為 true true &&其它布爾值時由其它布爾值決定真假
 - */
 - private Predicate<T> predicate = t -> true;
 - /**
 - * 添加一個校驗策略,可以無限續(xù)杯😀
 - *
 - * @param predicate the predicate
 - * @return the validator
 - */
 - public Validator<T> with(Predicate<T> predicate) {
 - this.predicate = this.predicate.and(predicate);
 - return this;
 - }
 - /**
 - * 執(zhí)行校驗
 - *
 - * @param t the t
 - * @return the boolean
 - */
 - public boolean validate(T t) {
 - return predicate.test(t);
 - }
 - }
 
邏輯不是很復(fù)雜,卻可以勝任各種復(fù)雜的斷言策略組合。接下來我們來對Predicate
Predicate
- @FunctionalInterface
 - public interface Predicate<T> {
 - /**
 - * 函數(shù)接口方法
 - */
 - boolean test(T t);
 - /**
 - * and 默認方法 相當(dāng)于邏輯運算符 &&
 - */
 - default Predicate<T> and(Predicate<? super T> other) {
 - Objects.requireNonNull(other);
 - return (t) -> test(t) && other.test(t);
 - }
 - /**
 - * negate 默認方法 相當(dāng)于邏輯運算符 !
 - */
 - default Predicate<T> negate() {
 - return (t) -> !test(t);
 - }
 - /**
 - * or 默認方法 相當(dāng)于邏輯運算符 ||
 - */
 - default Predicate<T> or(Predicate<? super T> other) {
 - Objects.requireNonNull(other);
 - return (t) -> test(t) || other.test(t);
 - }
 - /**
 - * 這個方法是提供給{@link Objects#equals(Object, Object)}用的,不開放給開發(fā)者
 - */
 - static <T> Predicate<T> isEqual(Object targetRef) {
 - return (null == targetRef)
 - ? Objects::isNull
 - : object -> targetRef.equals(object);
 - }
 - }
 
斷言函數(shù)接口提供了test方法供我們開發(fā)實現(xiàn),同時提供了and、negate、or分別對應(yīng)Java中的邏輯運算符&&、!、||。完全滿足了布爾型變量運算,在需要多個條件策略組合時非常有用。
總結(jié)
今天通過演示了Predicate
- if (Objects.equals(bool,true)){
 - //TODO
 - }
 
本文轉(zhuǎn)載自微信公眾號「碼農(nóng)小胖哥」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系碼農(nóng)小胖哥公眾號。

















 
 
 








 
 
 
 