When using lombok @Data (which adds EqualsAndHashCode)
It adds canEqual
method
protected boolean canEqual(Object other) { return other instanceof Exercise; }
which is only called once:
if (!other.canEqual((Object)this)) return false;
I search and found discussions about access level
If you implement equals and hashCode in a non-final class the safest thing we can do is add the can equal the way we do. Since we don't add any field the costs, especially if the method is protected, are slim.
But why do we need this generated method ? can't it be inline?
@EqualsAndHashCode annotation enables you to avoid having to manually write equals() and hashcode() methods in Java classes.
The annotation @Data with inheritance produces the next warning: Generating equals/hashCode implementation but without a call to superclass, even though this class does not extend java.
[Java] Annotation Type EqualsAndHashCode. Class annotation used to assist in creating appropriate equals() and hashCode() methods. The @EqualsAndHashCode annotation instructs the compiler to execute an AST transformation which adds the necessary equals and hashCode methods to the class.
If you need to write your own equals methods, you should always override canEqual if you change equals and hashCode . NEW in Lombok 1.14. 0: To put annotations on the other parameter of the equals (and, if relevant, canEqual ) method, you can use onParam=@__({@AnnotationsHere}) . Be careful though!
The canEqual
method is defined in a paper entitled How to Write an Equality Method in Java. This method is meant for allowing to redefine equality on several levels of the class hierarchy while keeping its contract:
The idea is that as soon as a class redefines
equals
(andhashCode
), it should also explicitly state that objects of this class are never equal to objects of some superclass that implement a different equality method. This is achieved by adding a methodcanEqual
to every class that redefinesequals
.
Seems like it was introduced in Lombok 0.10, as described in the @EqualsAndHashCode
documentation:
NEW in Lombok 0.10: Unless your class is
final
and extendsjava.lang.Object
, lombok generates acanEqual
method which means JPA proxies can still be equal to their base class, but subclasses that add new state don't break the equals contract.
And the documentation goes a bit further, referencing the paper quoted above:
The complicated reasons for why such a method is necessary are explained in this paper: How to Write an Equality Method in Java. If all classes in a hierarchy are a mix of scala case classes and classes with lombok-generated equals methods, all equality will 'just work'. If you need to write your own
equals
methods, you should always overridecanEqual
if you changeequals
andhashCode
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With