使用 lombok 时 @Data (添加 EqualsAndHashCode )
它添加了canEqual
方法
protected boolean canEqual(Object other) { return other instanceof Exercise; }
只调用一次:
if (!other.canEqual((Object)this)) return false;
我搜索并找到了discussions关于访问级别
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.
但是为什么我们需要这个生成的方法呢?不能内联吗?
最佳答案
canEqual
方法在题为 How to Write an Equality Method in Java 的论文中定义.此方法旨在允许在类层次结构的多个级别上重新定义相等性,同时保持其契约(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
.
它似乎是在 Lombok 0.10 中引入的,如 @EqualsAndHashCode
中所述文档:
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.
文档更进一步,引用了上面引用的论文:
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
.
关于java - 为什么 lombok 添加 canEqual 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263870/