A good rule suggestion:
@Override equals() MUST compare getClass() OR be final.
-
why
Assuming this is accurate: (sorry to have bothered you if it is not accurate)
https://medium.com/@akash746/instanceof-vs-getclass-in-equals-method-in-java-3e90ec60a9cc
" Use instanceof in the equals method if you cannot override it. Either make the method or the class final. Otherwise getClass() is the only way to go to guarantee that the contract for Object.equals is fulfilled." -
Noncompliant Code Example
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (!(o instanceof User)) return false;
User user = (User) o;
return id == user.id
&& (name.equals(user.name)
&& email.equals(user.email));
}
- Complaint Solution
public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (this.getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id
&& (name.equals(user.name)
&& email.equals(user.email));
}
- Other Compliant Solution
final public boolean equals(Object o) {
if (this == o) return true;
if (o == null) return false;
if (!(o instanceof User)) return false;
User user = (User) o;
return id == user.id
&& (name.equals(user.name)
&& email.equals(user.email));
}
-
external references and/or language specifications
seems similar to https://rules.sonarsource.com/java/RSPEC-1206 -
type : Bug, Vulnerability, Code Smell ?
Bug -
tags
minor -
related topic
assuming this is accurate:
https://javarevisited.blogspot.com/2015/12/10-points-about-instanceof-operator-in-java-example.html
if the object relates to hibernate, it seems like it should never compare getClass() because that would always be false… Might be another “good rule” but I’m not sure if Hibernate specific rules exist, or if the rule could generically detect somehow that the compared object is expected to be a proxy object…
EDIT
Thanks for the feedback, I have improved the use of markdown some…
I agree that this could be closed as a duplicate of any one of these.
https://jira.sonarsource.com/browse/RSPEC-2162
https://jira.sonarsource.com/browse/RSPEC-2161
https://jira.sonarsource.com/browse/RSPEC-2097
I’m not seeing how to close it (or delete it) myself.