java - 为什么 lombok 添加 canEqual 方法

标签 java equals lombok

使用 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 (and hashCode), 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 method canEqual to every class that redefines equals.


它似乎是在 Lombok 0.10 中引入的,如 @EqualsAndHashCode 中所述文档:

NEW in Lombok 0.10: Unless your class is final and extends java.lang.Object, lombok generates a canEqual 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 override canEqual if you change equals and hashCode.

关于java - 为什么 lombok 添加 canEqual 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58263870/

相关文章:

java - 如何在 HierarchicalStreamReader 转换器中使用 xml 标签获取 xml 元素的值

java - 调用方法时获取扩展父类(super class)的子类的实例

java 。 HtmlUnitDriver。下拉窗口问题

java - 对常量对象值使用赋值而不是相等

java - 如何在 equals() 中有效地使用 float ?

java - Lombok 私有(private) build 者

java - 处理父类(super class)型的所有子类型

java - 当 EObject 包含无序的 EList 时如何比较它们之间的相等性?

java - 具有复杂类结构的 Lombok 构建器继承

spring - Project Lombok @Slf4j 外部配置