Redefining equals and determining which field was unequal

I am overriding the equals method of a class to compare two objects since I want to compare all of its fields. If two objects are unequal, is there a way to find out which of the fields was unequal, making the objects unequal?

+3


source to share


2 answers


You can write a method in a class that returns an object of the same type with a difference or null for each data item. Or, you can find a library to do it for you. Try http://javers.org



+2


source


Create a class to strip data of fields like this (or use Map

):

class FieldsContainer<F,V>{
    private F field;
    private V value;
    public FieldsContainer(F field, V value) {
        this.field = field;
        this.value = value;
    }
    public FieldsContainer(){}
    public F getField() {
        return field;
    }
    public void setField(F field) {
        this.field = field;
    }
    public V getValue() {
        return value;
    }
    public void setValue(V value) {
        this.value = value;
    }

}

      

and then in equals ():



public boolean equals(Object obj) {
        ...
        } else if (!field1.equals(other.field1)){
            fieldsContainer=new FieldsContainer("fieldName1", field1);
            return false;
        }
        if (field2 != other.field2){
            fieldsContainer=new FieldsContainer("fieldName2", field2);
            return false;
        }
        fieldsContainer=null;
        return true;
    }

      

and basically:

if(!obj1.equals(obj2)){
    fieldsContainer.getField();
    fieldsContainer.getValue();
    //Your stuff
}

      

0


source







All Articles