Sonar always flags it with rule java:S2162 because it thinks we are comparing unrelated classes but in my opinion it is a very valid check that should not be flagged. Indeed i am not comparing where sonar thinks i do i just try to resolve the class in question if it is behind a proxy.
public final boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null) {
return false;
}
Class<?> oEffectiveClass = o instanceof HibernateProxy ? ((HibernateProxy) o).getHibernateLazyInitializer()
.getPersistentClass() : o.getClass();
Class<?> thisEffectiveClass = this instanceof HibernateProxy ?
((HibernateProxy) this).getHibernateLazyInitializer()
.getPersistentClass() : this.getClass();
if (thisEffectiveClass != oEffectiveClass) {
return false;
}
MyJpaEntity that = (MyJpaEntity) o;
return getId() != null && Objects.equals(getId(), that.getId());
}
I am afraid that is the case because the Proxy is created in the background on runtime.
What then is imported is HibernateProxy that could also be a indicator and class names clould end with entity but in my opinion that is not always the case and should not be considered
In fact, if we correctly detect the comparison (not the class resolution, which is what is flagged), it would work if we only consider the equals method instead of the instanceof class resolution.