Javers比较String null和""空字符串

时间:2018-01-25 08:41:31

标签: java javers

是否可以配置Javers,以便在比较具有值为null或""的String属性的两个对象时。 (空)字符串,它不会发现任何差异。基本上对待null和""空字符串相同。 例如:

Class Phone 
{
    String phoneNumber;
    Phone(phoneNumber)
    {
         this.phoneNumber = phoneNumber;
    }

}
Phone phoneNumber = new PhoneNumber("");
Phone phoneNumber1 = new PhoneNumber(null);

我希望当Javers比较这两个对象时,它将没有显示出差异。

2 个答案:

答案 0 :(得分:1)

您可以为值注册自定义比较器。它在JaVers doc中解释过 - https://javers.org/documentation/domain-configuration/#ValueType

Javers javers = JaversBuilder.javers()
        .registerValue(String.class, (a, b) ->  StringUtils.equals(a,b)).build();

答案 1 :(得分:0)

您可以在java中覆盖equals方法。示例代码如下。

import java.util.*; 
import java.io.*;

class Phone 
{
    String phoneNumber;
    Phone(String phoneNumber)
    {
         this.phoneNumber = phoneNumber;
    }

    public boolean equals(Object object) {
        if(object instanceof Phone) {
            String phoneNumber = ((Phone)object).phoneNumber;
            if(Utility.isNullOrEmpty(phoneNumber) && Utility.isNullOrEmpty(this.phoneNumber)) {
               return true; 
            } else if ( phoneNumber != null && phoneNumber.equals(this.phoneNumber)) {
                return true; 
            } else if ( this.phoneNumber != null && this.phoneNumber.equals(phoneNumber)){
                 return true; 
            }
            return false;
        } else {
            return false;
        }
    }

}


class Main {  

  public static void main (String[] args) {  
    // keep this function call here     
      Phone ph1 = new Phone("");
      Phone ph2 = new Phone(null);

      if(ph1.equals(ph2)) {
          System.out.println("ph1 and ph2 are equal.");
      }

      Phone ph3 = new Phone("123456789");
      Phone ph4 = new Phone("123456789");

      if(ph3.equals(ph4)) {
          System.out.println("ph3 and ph4 are equal.");
      }

      if(ph3 == ph2) {
          System.out.println("ph3 and ph2 are equal.");
      } else {
          System.out.println("ph3 and ph2 are not equal.");
      }
  }   

}

class Utility {

    public static boolean isNullOrEmpty(String str) {
        return (str == null || str.isEmpty());
    }

}