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

后端 未结 6 2065
萌比男神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:56

    How about you write unittests for each class you want to protect. The unit tests should

    1. Use reflection to count the number of fields, and compare with locally stored field names (and types).
    2. If a change in number of fields (or type of fields) has been detected, then invoke hashcode. If the value is the same, then fail the test case. Alert the developer that fields of a class have been changed, and that the developer should : Update the equals and Hashcose, and update the unittest.
    3. Make sure the unittest runs in a nightly build.

提交回复
热议问题