本文介绍了使用unitils ReflectionComparator忽略字符串中的大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 unitils 工具通过ReflectionComparator进行深层对象比较:

I'm using unitils tool for deep objects comparing, via ReflectionComparator:

ReflectionComparatorMode[] modes = {ReflectionComparatorMode.LENIENT_ORDER, ReflectionComparatorMode.IGNORE_DEFAULTS};
ReflectionComparator comparator = ReflectionComparatorFactory.createRefectionComparator(modes);
Difference difference = comparator.getDifference(oldObject, newObject);

事实证明,此ReflectionComparator不会忽略String字段值中的大小写.在ReflectionComparatorMode枚举中,没有用于此目的的sprecial模式:

It turns out that this ReflectionComparator doesn't ignore case in String fields values. And there isn't sprecial mode for this purpose in ReflectionComparatorMode enum:

public enum ReflectionComparatorMode {
    IGNORE_DEFAULTS,
    LENIENT_DATES,
    LENIENT_ORDER
}

任何想法,如何实现?

推荐答案

ReflectionComparator的工作方式的研究为我提供了这个可行的解决方案.简而言之,我们必须添加另一个特殊的Comparator对象来处理比较器链中的String对象.

Investigation of how ReflectionComparator works gave me this workable solution. Saying in brief, we have to add another one special Comparator object for dealing with String objects in comparators chain.

此外,我们还必须做一些 bedlam ,以便从ReflectionComparatorFactory中提取一种所需的protected静态方法,以减少代码加倍.

Also we have to do some bedlam with extracting one needed protected static method from ReflectionComparatorFactory in order to reduce code doubling.

ReflectionComparatorMode[] modes = {ReflectionComparatorMode.LENIENT_ORDER, ReflectionComparatorMode.IGNORE_DEFAULTS};

List<org.unitils.reflectionassert.comparator.Comparator> comparators = new ArrayList<>();
    comparators.add(new Comparator() {
         @Override
         public boolean canCompare(Object left, Object right) {
               return left instanceof String && right instanceof String;
         }

         @Override
         public Difference compare(Object left, Object right, boolean onlyFirstDifference, ReflectionComparator reflectionComparator) {
               return  ((String) left).equalsIgnoreCase((String) right) ? null : new Difference("Non equal values: ", left, right);
         }
});

comparators.addAll(
    new ReflectionComparatorFactory() {
        public List<Comparator> getComparatorChainNonStatic(Set<ReflectionComparatorMode> modes) {
               return getComparatorChain(modes);
        }
    }.getComparatorChainNonStatic(asSet(modes)));

ReflectionComparator comparator = new ReflectionComparator(comparators);

这篇关于使用unitils ReflectionComparator忽略字符串中的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 14:58