Complicated equals() method
To easily implement the equals method , you can use the EqualsBuilder class . Here are some examples to show how it works.
Setting specific fields for comparison:
public class User {
private String name;
private String email;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User user)) return false;
return new EqualsBuilder().append(name, user.name).append(email, user.email).isEquals();
}
}
Also, this class can compare objects through reflection:
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
Complicated hashCode() method
To implement the hashCode method , you must use the HashCodeBuilder class .
Field selection:
@Override
public int hashCode() {
return new HashCodeBuilder(17, 37)
.append(name)
.append(email)
.toHashCode();
}
Using reflection to build hash code:
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
We use reflection and ignore certain fields:
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this, "name");
}
Complicated toString() method
In a similar way, you can even implement the toString() method . Again, we use the ToStringBuilder class .
The fields are set as in the previous two cases:
@Override
public String toString() {
return new ToStringBuilder(this)
.append(name)
.append(email)
.toString();
}
Result example:
org.example.User@4b67cf4d[name=John,email=email@email.com]
You can also specify field names explicitly:
@Override
public String toString() {
return new ToStringBuilder(this)
.append("nameUser", name)
.append("emailUser", email)
.toString();
}
Result example:
org.example.User@4b67cf4d[nameUser=John,emailUser=email@email.com]
You can change the text style using the settings:
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
.append(name)
.append(email)
.toString();
}
Result example:
User[John,emailUser=email@email.com]
There are several styles like JSON, no Classname, short and others.
Using reflection:
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
Using reflection and specifying a specific style:
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
GO TO FULL VERSION