在@Data注释lombok上使用继承警告等于/ hashCode

Pau*_*Pau 65 java lombok

我有一个继承自其他的实体.另一方面,我使用lombok项目来减少样板代码,所以我把@Data注释.@Data带继承的注释会产生下一个警告:

生成equals/hashCode实现但不调用超类,即使此类不扩展java.lang.Object.如果这是故意的,请添加@EqualsAndHashCode(callSuper=false)到您的类型.

是否可以添加注释@EqualsAndHashCode (callSuper = true)@EqualsAndHashCode (callSuper = false)?如果没有添加,是哪一个callSuper=falsecallSuper=true

Roe*_*ker 88

默认值false.如果您没有指定它并忽略警告,那就是您获得的那个.

是的,建议@EqualsAndHashCode在带@Data注释的类上添加注释,这些注释类扩展了除Object以外的其他类.我不能告诉你,如果你需要true或者false,这取决于你的班级等级,并且需要根据具体情况进行检查.

但是,对于项目或包,lombok.config如果它不是Object的直接子类,则可以配置调用super方法.

lombok.equalsAndHashCode.callSuper = call
Run Code Online (Sandbox Code Playgroud)

请参阅配置系统文档,了解其工作原理以及支持的配置键的@EqualsEndHashCode文档.

披露:我是一名lombok开发者.

  • @Roel 我想知道为什么默认值为 false。我会预料到相反的情况。另外,是否有等效的方法让 toString() 默认调用 super ?我看到我可以执行“@ToString(callSuper=true)”,但没有看到任何此类配置设置。谢谢。 (3认同)

nos*_*ame 34

@EqualsAndHashCode(callSuper=true) 应该解决警告.

  • @AnnaKlein 我不这么认为。实际上这个答案应该是评论,这里没有新信息,你可以在我的问题中找到。我确实知道`@EqualsAndHashCode` 解决了警告。 (5认同)
  • 这应该是公认的答案,因为我认为不应该执行 Roel 的建议“lombok.equalsAndHashCode.callSuper = call”,而是应该为每个类做出决定。 (2认同)

EvR*_*R2f 15

如果您还想比较超类的成员,请使用@EqualsAndHashCode(callSuper=true). 但是,如果你只是想在当前类比较字段,你可以使用@EqualsAndHashCode(callSuper=false)它是默认选项。

如果您使用Delombok -feature,您可以看到不同之处在于,当设置为true这一行时,它会添加到生成的equals方法中if (!super.equals(o)) return false;。如果在比较两个对象时应考虑超类中的成员,则必须将其设置为 true 才能正确比较。


Ada*_*ise 8

主要的原始问题是:

是否建议添加注释@EqualsAndHashCode(callSuper = true)或@EqualsAndHashCode(callSuper = false)?

可接受的答案基本上是:

...那要看...

为了对此进行扩展,@ EqualsAndHashCode的文档提供了一些可靠的选择指南。特别是,恕我直言:

By setting callSuper to true, you can include the equals and hashCode methods of your superclass in the generated methods. For hashCode, the result of super.hashCode() is included in the hash algorithm, and forequals, the generated method will return false if the super implementation thinks it is not equal to the passed in object. Be aware that not all equals implementations handle this situation properly. However, lombok-generated equals implementations do handle this situation properly, so you can safely call your superclass equals if it, too, has a lombok-generated equals method.

To distill this down a bit: Chose 'callSuper=true' if you are inheriting from a superclass that either has no state information, or itself is using the @Data annotation, or has implementations of equals/hash that "handle the situation properly" - which I interpret to mean returning a proper hash of the state values.

  • 我认为这个答案很好地解释了如何在 callSuper = false 和 callSuper = true 之间进行选择。 (2认同)