35
I often use apache HashCodeBuilder and EqualsBuilder for object equality using reflection, but recently I a colleague told me that using reflection may cause a huge performance hit if the entity contains lots of properties. Worried that I may be using a wrong implementation, my question is, which of the following approach would you prefer? And why?
public class Admin {
private Long id;
private String userName;
public String getUserName() {
return userName;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Admin)) {
return false;
}
Admin otherAdmin = (Admin) o;
EqualsBuilder builder = new EqualsBuilder();
builder.append(getUserName(), otherAdmin.getUserName());
return builder.isEquals();
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(getUserName());
return builder.hashCode();
}
}
Vs.
public class Admin {
private Long id;
private String userName;
public String getUserName() {
return userName;
}
@Override
public boolean equals(Object o) {
return EqualsBuilder.reflectionEquals(this, o, Arrays.asList(id));
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, Arrays.asList(id));
}
}