覆盖等于并找出哪个字段不相等

时间:2014-12-10 20:54:18

标签: java class object override equals

我正在重写equals方法来比较两个对象,因为我想比较它的所有字段。如果两个对象不相等,有没有办法找出哪些字段是不相等的,因为对象不相等?

1 个答案:

答案 0 :(得分:0)

创建类来存储这样的字段信息(或使用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;
    }

}

然后在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;
    }

并在主要:

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