簡體   English   中英

使用unitils ReflectionComparator忽略字符串中的大小寫

[英]Ignoring case in strings with unitils ReflectionComparator

我使用unitils工具通過ReflectionComparator進行深層對象比較:

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

事實證明,此ReflectionComparator不會忽略String字段值中的大小寫。 ReflectionComparatorMode枚舉中,沒有用於此目的的串行模式:

public enum ReflectionComparatorMode {
    IGNORE_DEFAULTS,
    LENIENT_DATES,
    LENIENT_ORDER
}

有什么想法,如何實現?

ReflectionComparatorMode沒有模擬模仿ignore_case行為的模式。 您沒有指定oldObjectnewObject的類型,但我想您可以在將它們傳遞給ReflectionComparator之前(將所有String字段都轉換為大寫或小寫)進行“ 規范化 ”,或者根據oldObject的特定類型實現自己的Java Comparator和newObject

看看這個

ReflectionComparator工作方式進行調查后,得出了這個可行的解決方案。 簡而言之,我們必須添加另一個特殊的Comparator對象來處理比較器鏈中的String對象。

此外,我們必須做一些喧鬧與提取一個需要protected從靜態方法ReflectionComparatorFactory為了減少代碼加倍。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM