最近在搞Excel导入,数据校验是少不了的,但是不同的数据字段有不同的校验策略,五花八门的,甚至不确定,没有办法使用JSR303。所以就搞一个校验策略工具,把校验策略抽象出来。这里尝试了Java 8 提供的一个断言函数接口java.util.function.Predicate
Predicate接口
Predicate的应用
先来看看效果:
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");
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
我拿校验字符串为例子,通过一系列的Predicate
public class UserServiceImpl implements UserService {
@Override
public boolean checkUserByName(String name) {
return false;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
对应的校验可以改为:
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");
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
好奇的同学该想知道是怎么实现的,Validator
import java.util.function.Predicate;
public class Validator<T> {
/**
* 初始化为 true true &&其它布尔值时由其它布尔值决定真假
*/
private Predicate<T> predicate = t -> true;
/**
* 添加一个校验策略,可以无限续杯😀
*
* @param predicate the predicate
* @return the validator
*/
public Validator<T> with(Predicate<T> predicate) {
this.predicate = this.predicate.and(predicate);
return this;
}
/**
* 执行校验
*
* @param t the t
* @return the boolean
*/
public boolean validate(T t) {
return predicate.test(t);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
逻辑不是很复杂,却可以胜任各种复杂的断言策略组合。接下来我们来对Predicate
Predicate
@FunctionalInterface
public interface Predicate<T> {
/**
* 函数接口方法
*/
boolean test(T t);
/**
* and 默认方法 相当于逻辑运算符 &&
*/
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
/**
* negate 默认方法 相当于逻辑运算符 !
*/
default Predicate<T> negate() {
return (t) -> !test(t);
}
/**
* or 默认方法 相当于逻辑运算符 ||
*/
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
/**
* 这个方法是提供给{@link Objects#equals(Object, Object)}用的,不开放给开发者
*/
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
断言函数接口提供了test方法供我们开发实现,同时提供了and、negate、or分别对应Java中的逻辑运算符&&、!、||。完全满足了布尔型变量运算,在需要多个条件策略组合时非常有用。
总结
今天通过演示了Predicate
if (Objects.equals(bool,true)){
//TODO
}
- 1.
- 2.
- 3.
本文转载自微信公众号「码农小胖哥」,可以通过以下二维码关注。转载本文请联系码农小胖哥公众号。