Subclass: object is not equal to an instance of a trivial subclass with equal fields

894 views
Skip to first unread message

AYUSHI SHARMA

unread,
Dec 24, 2015, 5:53:41 AM12/24/15
to equalsverifier
I am using EqualsVerifier to write JUnits for my JPA entities. As suggested here, I modified equals method of my POJOs to use 'instance Of' instead of getClass().

However SonarQube seems to dislike it and it's highlighted as a critical bug. It says, "equals" methods should be symmetric and work for subclasses.

I have to revert back to using getClass() now. Since it's a JPA entity, I can't make the class final. How can i make the EqualsVerifier work with getClass().



Jan Ouwens

unread,
Dec 24, 2015, 6:04:00 AM12/24/15
to equalsverifier
Hi,

You can call EqualsVerifier like this:

EqualsVerifier.forClass(Something.class).usingGetClass().verify();

That said, this is not a good thing to do for JPA entities, because JPA frameworks generate their own subclasses (which is why they can't be final). If you use getClass() in your equals method to compare entities, such a subclass can never be equal to an object of the same class that you instantiate yourself, even if all the fields are equal. That's why I recommend using instanceof.

SonarQube says that using instanceof leads to asymmetric equals methods. That's *only* true if you override equals, which is something that you usually don't have to do. Therefore, if you want to have an instanceof check without worrying about symmetry, you can also make your equals and hashCode methods final. (I hope that SonarQube picks up on that though.) Josh Bloch (author of Effective Java) also favors the instanceof approach.


Jan


--
You received this message because you are subscribed to the Google Groups "equalsverifier" group.
To unsubscribe from this group and stop receiving emails from it, send an email to equalsverifie...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Message has been deleted

AYUSHI SHARMA

unread,
Dec 28, 2015, 5:27:11 AM12/28/15
to equalsverifier

Thanks for your prompt reply and a reasonable explanation Mr. Ouwens. 

You're right. Using instanceof check along with making hashcode and equals method final looks the better approach. Will try and see how SonaQube reacts to that.
Reply all
Reply to author
Forward
0 new messages