簡體   English   中英

如何比較兩個復雜的對象並忽略空字符串和空字符串?

[英]How to compare two complex object and ignore both null and empty string?

我需要聲明兩個復雜的對象,其中可能包含原始對象和n個對象。 所以我用谷歌搜索並選擇了一個unitils圖書館。 但是我有一個條件,我需要將null和空字符串都視為相等。但是這里它僅支持ReflectionComparatorMode.IGNORE_DEFAULTS 場景:

 public class AssertVerify {

    public static void main(String args[]){

    CustomerPojo cuPojo1=new CustomerPojo();
    CustomerPojo cuPojo2=new CustomerPojo();

    cuPojo1.setCustomerName("obuli");
    cuPojo1.setCustomerAge("20");
    cuPojo1.setAddress("");

    cuPojo2.setCustomerName("obuli");
    cuPojo2.setCustomerAge("20");


    /**
     * Asserting  two pojos
     */     
    ReflectionAssert.assertReflectionEquals(cuPojo1, cuPojo2,
            ReflectionComparatorMode.LENIENT_DATES ,ReflectionComparatorMode.IGNORE_DEFAULTS);

}       

錯誤:

 junit.framework.AssertionFailedError: 
 Expected: CustomerPojo<customerName="obuli", customerAge="20", Address="">
  Actual: CustomerPojo<customerName="obuli", customerAge="20", Address=null>

  --- Found following differences ---
  Address: expected: "", actual: null

   --- Difference detail tree ---
  expected: CustomerPojo<customerName="obuli", customerAge="20", Address="">
   actual: CustomerPojo<customerName="obuli", customerAge="20",   Address=null>

  Address expected: ""
  Address   actual: null


   at junit.framework.Assert.fail(Assert.java:47)
    at      org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals(ReflectionA   ssert.java:136)at       org.unitils.reflectionassert.ReflectionAssert.assertReflectionEquals(ReflectionA   ssert.java:99)
atcom.assertion.verify.AssertVerify.main(AssertVerify.java:52) 

 picked up _JAVA_OPTIONS: -Djava.net.preferIPv4Stack=true

我需要添加一個將空字符串和空字符串視為相等的規則。

有沒有可能針對我的情況的解決方案。

正如Gremash提到的那樣,您應該實現可比的接口並覆蓋equals方法,不要着急,確保您知道自己在做什么,因為當您使用實現此接口的自己的對象並使用您的方法時,可能會使集合中的工作混亂。在Core Java 1-2系列中(如果可能的話)對此問題進行了討論,並對其進行了詳細說明。 有一些規則,例如equals()必須定義一個等價關系(它必須是自反的,對稱的和可傳遞的),此外: 在Java中重寫equals和hashCode時應考慮哪些問題?

我認為最好還是采用這種方式,然后再依賴其他庫。

暫無
暫無

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

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