问题描述
我正在使用 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忽略字符串中的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!