位置:org.springframework.util
�实现接口:无
继承类:无
作用:一个简单的实例过滤器,它根据包含和排除元素的集合检查给定实例是否匹配。

一、效果

  1. // 验证一个字符串是否能通过过滤器的匹配
  2. public void test1() throws Exception {
  3. ArrayList<String> includes = new ArrayList<>();
  4. includes.add("javascript");
  5. includes.add("html");
  6. includes.add("css");
  7. ArrayList<String> excludes = new ArrayList<>();
  8. excludes.add("c#");
  9. excludes.add("php");
  10. excludes.add("go");
  11. InstanceFilter<String> filter = new InstanceFilter<>(includes, excludes, false);
  12. boolean m = filter.match("java");
  13. System.out.println(m); // 输出:false(不匹配)
  14. }

二、API

  1. /**
  2. * instance: 被比较元素
  3. */
  4. public boolean match(T instance) {
  5. Assert.notNull(instance, "Instance to match must not be null");
  6. // 包含的集合不为空
  7. boolean includesSet = !this.includes.isEmpty();
  8. // 排除的集合不为空
  9. boolean excludesSet = !this.excludes.isEmpty();
  10. // 包含和排除的集合都为空时,期望的返回 boolean 值
  11. if (!includesSet && !excludesSet) {
  12. return this.matchIfEmpty;
  13. }
  14. // 调用 protected match 方法比较集合内是否包含该元素,调用内部 集合 match 匹配方法
  15. boolean matchIncludes = match(instance, this.includes);
  16. boolean matchExcludes = match(instance, this.excludes);
  17. // 如果包含集合为空,返回取反的排除集合匹配结果。
  18. // 包含集合为空,排除集合包含返回 false,不包含返回 true
  19. if (!includesSet) {
  20. return !matchExcludes;
  21. }
  22. // 排除集合为空,返回包含集合中是否匹配该元素
  23. if (!excludesSet) {
  24. return matchIncludes;
  25. }
  26. // 包含和排除集合都不为空时,只有包含集合中匹配且排除集合中不匹配才返回 true
  27. return matchIncludes && !matchExcludes;
  28. }
  29. // 可被子类覆盖重写,查找集合中是否包含该元素,使用遍历匹配方法,调用内部方法。
  30. protected boolean match(T instance, Collection<? extends T> candidates) {
  31. for (T candidate : candidates) {
  32. if (match(instance, candidate)) {
  33. return true;
  34. }
  35. }
  36. return false;
  37. }
  38. // 比较元素是否相等的方法
  39. protected boolean match(T instance, T candidate) {
  40. return instance.equals(candidate);
  41. }

三、总结

InstanceFilter是一个简单的实例过滤器,它根据包含和排除元素的集合检查给定实例是否匹配。 子类可能需要覆盖 match 方法来提供自定义匹配算法。

四、补充

同一包下的类ExceptionTypeFilter实现了InstanceFilter,覆盖了match方法:

  1. @Override
  2. protected boolean match(Class<? extends Throwable> instance, Class<? extends Throwable> candidate) {
  3. return candidate.isAssignableFrom(instance);
  4. }

Class类 public native boolean isAssignableFrom(Class<?> cls) 确定此 Class 对象表示的类或接口是否与指定的 Class 参数表示的类或接口相同,或是其超类或超接口。如果是则返回 true;否则返回false。


参考资料: Spring下的Util - InstanceFilter