Ignoring case in strings with unitils ReflectionCo

2019-07-20 19:17发布

问题:

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