Ignoring case in strings with unitils ReflectionComparator

我与影子孤独终老i 提交于 2019-12-11 03:32:41

问题


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);

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
}

Any ideas, how it could be achieved?


回答1:


ReflectionComparatorMode has no mode to mimic ignore_case behavior. You do not specify the types of oldObject and newObject but I guess you can either 'normalize' them before passing them to ReflectionComparator (convert all String fields to either upper or lower case) or implement your own Java Comparator based on the specific type of oldObject and newObject.

Check out this.




回答2:


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.

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);


来源:https://stackoverflow.com/questions/29769568/ignoring-case-in-strings-with-unitils-reflectioncomparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!