What are ways to keep hashCode/equals consistent with the business definition of the class?

后端 未结 6 2154
萌比男神i
萌比男神i 2021-02-01 19:12

Object javadocs and Josh Bloch tell us a great deal about how hashCode/equals should be implemented, and good IDEs will handle fields of various types correctly. Some discussio

6条回答
  •  耶瑟儿~
    2021-02-01 19:52

    Sounds like what you're looking for is an addon or feature in an IDE that performs the analysis of the classes and generates warnings if the equals() and hashCode() methods do not reference all the relevant fields.

    This would basically move the reflection overhead to the IDE rather than let it have the cost during run-time.

    Unfortunately, I don't know of any addon that does this, though I'll certainly have a look.

    On the other hand, how would such an automated tool know which fields are relevant for business logic? You'd probably need to mark irrelevant fields with something like an annotation, otherwise you could find yourself with warnings you can't get rid of, but that you know are incorrect.

    Edit: This answer is not useful, so I'm just compiling here the really useful suggestions from better answers:

    • Project Lombok - Eclipse addon that also works with build tools to provide automatic generation of equals(), hashCode() and other boiler-plate code - since it's generated at compile-time, any changes to the class will automatically update these methods too
    • equalsverifier - Provides a way to automatically unit test equals() with reflection - doesn't support testing hashCode()

提交回复
热议问题