当你的类没有继承至任何类(非 java.lang.Object , 当然任何类都是继承于Object类的),而你却将callSuer置为true, 这会产生编译错误(译者注: java: Generating equals/hashCode with a supercall to java.lang.Object is pointless. )。因为这会使得生成的 equals 和 hashCode 方法实现只是简单的继承至Object类的方法,只有相同的对象并且相同的hashCode才会判定他们相等。若你的类继承至另一个类又没有设置callSuper, 则会产品一个告警,因为除非超类没有(或者没有跟相等相关的)字段,否则lombok无法为你生成考虑超类声明字段的实现。你需要编写自己的实现,或者依赖callSuper的链式功能。你也可以使用配置关键字 lombok.equalsAndHashCode.callSuper .(译者注:配置关键字这里还没搞明白!!!)
NEW in Lombok 0.10:
除非你的类是 final 类型并且只是继承至java.lang.Object, 否则lombok会生成一个 canEqual 方法,这以为着JPA代理仍然可以等于他们的基类,但是添加新状态的子类不会破坏equals契约。下文解释了为什么需要这种方法的复杂原因: How to Write an Equality Method in Java 。如果层次结构中的所有类都是scala case类和带有lombok生成的equals方法的类的混合,则所有的相等都能正常工作。如果你需要编写自己的equals方法,那么如果更改 equals 和 hashCode 方法,都应该始终覆盖 canEqual .
protectedbooleancanEqual(final Object other){ return other instanceof EqualsAndHashCodeExample; }
publicinthashCode(){ int PRIME = true; int result = 1; Object $name = this.getName(); int result = result * 59 + ($name == null ? 43 : $name.hashCode()); long $score = Double.doubleToLongBits(this.score); result = result * 59 + (int)($score >>> 32 ^ $score); result = result * 59 + Arrays.deepHashCode(this.tags); return result; }
protectedbooleancanEqual(final Object other){ return other instanceof EqualsAndHashCodeExample.Square; }
publicinthashCode(){ int PRIME = true; int result = super.hashCode(); result = result * 59 + this.width; result = result * 59 + this.height; return result; } } }
注意
超类不加callSuper且不手动覆写,上述的代码,通过下面的代码测试
1 2 3 4 5 6 7 8
publicstaticvoidmain(String[] args){
Square square1 = new Square(1, 2); Square square2 = new Square(1, 2); // false System.out.println(square1.equals(square2)); }