Reputation: 6053
I am overriding equals method of a class to compare two objects since I want to compare all the fields of it. If two objects are unequal, is there a way to find out which of the fields were unequal due to which the objects are unequal?
Upvotes: 3
Views: 484
Reputation: 1354
Create class to strore fields information 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 in main:
if(!obj1.equals(obj2)){
fieldsContainer.getField();
fieldsContainer.getValue();
//Your stuff
}
Upvotes: 0
Reputation: 139
You could write a method in the class that returns an object of the same type with either the difference or null for each data member. Or you can find a library that does it for you. Try http://javers.org
Upvotes: 2