Warning equals/hashCode on @Data annotation lombok with inheritance

后端 未结 4 446
轻奢々
轻奢々 2020-12-23 03:01

I have a entity which inherits from other. On other hand, I\'m using lombok project to reduce boilerplate code, so I put @Data annotation. The annotation

4条回答
  •  独厮守ぢ
    2020-12-23 03:11

    The main original question is:

    Is it advisable to add annotation @EqualsAndHashCode (callSuper = true) or @EqualsAndHashCode (callSuper = false)?

    The accepted answer is basically just:

    ...that depends...

    To expand on that, the documentation on @EqualsAndHashCode has some solid guidance on which to choose. Especially this, IMHO:

    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.

提交回复
热议问题