要轻松实现对象的equals方法,可以使用EqualsBuilder类。
选择字段:
@Override public boolean equals(Object obj) { if(!(obj instanceof MyClass)) { return false; } MyClass theOther = (MyClass) obj; EqualsBuilder builder = new EqualsBuilder(); builder.append(field1, theOther.field1); builder.append(field2, theOther.field2); builder.append(field3, theOther.field3); return builder.isEquals(); }
使用反射:
@Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj, false); }
布尔参数用于指示是否等于应检查瞬态字段。
使用反射避免某些字段:
@Override public boolean equals(Object obj) { return EqualsBuilder.reflectionEquals(this, obj, "field1", "field2"); }