记录Spring下的Util - InstanceFilter
位于org.springframework.util
包下;
Spring 文档介绍
一个简单的实例过滤器,它根据包含和排除元素的集合检查给定实例是否匹配。 子类可能需要覆盖 match 方法来提供自定义匹配算法。
类中方法
- 构造函数
只有一个三个参数的构造函数
/**
* includes:被比较的元素希望存在的集合
* excludes: 被比较元素不希望存在的集合
* matchIfEmpty:includes和excludes都为空时的默认返回值
*/
public InstanceFilter(@Nullable Collection<? extends T> includes,
@Nullable Collection<? extends T> excludes, boolean matchIfEmpty) {
this.includes = (includes != null ? includes : Collections.emptyList());
this.excludes = (excludes != null ? excludes : Collections.emptyList());
this.matchIfEmpty = matchIfEmpty;
}
- 方法
三个match的多态方法,一个为 public,其它两个为 protected,protected方法是随着业务不同可以进行继承覆盖实现的。另外一个 toString方法。
/**
* instance: 被比较元素
*/
public boolean match(T instance) {
Assert.notNull(instance, "Instance to match must not be null");
// 包含的集合不为空
boolean includesSet = !this.includes.isEmpty();
// 排除的集合不为空
boolean excludesSet = !this.excludes.isEmpty();
// 包含和排除的集合都为空时,期望的返回 boolean 值
if (!includesSet && !excludesSet) {
return this.matchIfEmpty;
}
// 调用 protected match 方法比较集合内是否包含该元素,调用内部 集合 match 匹配方法
boolean matchIncludes = match(instance, this.includes);
boolean matchExcludes = match(instance, this.excludes);
// 如果包含集合为空,返回取反的排除集合匹配结果。
// 包含集合为空,排除集合包含返回 false,不包含返回 true
if (!includesSet) {
return !matchExcludes;
}
// 排除集合为空,返回包含集合中是否匹配该元素
if (!excludesSet) {
return matchIncludes;
}
// 包含和排除集合都不为空时,只有包含集合中匹配且排除集合中不匹配才返回 false
return matchIncludes && !matchExcludes;
}
// 可被子类覆盖重写,查找集合中是否包含该元素,使用遍历匹配方法,调用内部方法。
protected boolean match(T instance, Collection<? extends T> candidates) {
for (T candidate : candidates) {
if (match(instance, candidate)) {
return true;
}
}
return false;
}
// 比较元素是否相等的方法
protected boolean match(T instance, T candidate) {
return instance.equals(candidate);
}