位置:org.springframework.util
�实现接口:无
继承类:无
作用:一个简单的实例过滤器,它根据包含和排除元素的集合检查给定实例是否匹配。
一、效果
// 验证一个字符串是否能通过过滤器的匹配
public void test1() throws Exception {
ArrayList<String> includes = new ArrayList<>();
includes.add("javascript");
includes.add("html");
includes.add("css");
ArrayList<String> excludes = new ArrayList<>();
excludes.add("c#");
excludes.add("php");
excludes.add("go");
InstanceFilter<String> filter = new InstanceFilter<>(includes, excludes, false);
boolean m = filter.match("java");
System.out.println(m); // 输出:false(不匹配)
}
二、API
/**
* 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;
}
// 包含和排除集合都不为空时,只有包含集合中匹配且排除集合中不匹配才返回 true
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);
}
三、总结
InstanceFilter是一个简单的实例过滤器,它根据包含和排除元素的集合检查给定实例是否匹配。 子类可能需要覆盖 match 方法来提供自定义匹配算法。
四、补充
同一包下的类ExceptionTypeFilter实现了InstanceFilter,覆盖了match方法:
@Override
protected boolean match(Class<? extends Throwable> instance, Class<? extends Throwable> candidate) {
return candidate.isAssignableFrom(instance);
}
Class类 public native boolean isAssignableFrom(Class<?> cls) 确定此 Class 对象表示的类或接口是否与指定的 Class 参数表示的类或接口相同,或是其超类或超接口。如果是则返回 true;否则返回false。