Reputation: 4504
Is there in java a more easy way to compare common fields(same name and type) of instances of different class without explicitly checking each field against another.
moo.getFoo() == doo.getFoo();
moo.getRoo().equals(doo.getRoo())
-
Class Moo {
private int foo;
private Object roo;
}
Class Doo {
private int foo;
private Object roo;
private String ho;
}
Or at least is it possible in that case
Class Doo extends Moo {
private String ho;
}
Upvotes: 2
Views: 396
Reputation: 3829
You could use the CompareToBuilder or EqualsBuilder from Apache Commons Lang. This Utilities create automatically the result for the compareTo(), equals() or hashCode() methods for all fields of the class.
public int compareTo(Object o) {
return CompareToBuilder.reflectionCompare(this, o);
}
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
Upvotes: 5