在阅读了(再次,很久以前就应该这样做)正确实现 equals 和 hashcode 后,我得出了这些结论,这对我有用:
如果是 JDK 7 之前的版本:更喜欢使用 Apache commons equalsbuilder 和 hashcodebuilder。 (或番石榴)。
他们的 javadoc 包含如何很好地使用它们的示例。
如果JDK 7++:使用新的Objects实用程序类
但是,如果为休眠编写出现一些特殊要求(请参阅下面的来源)
其中推荐使用实例化代替getClass,由于 hibernate 创建了延迟加载的子类的代理。
但据我了解,如果这样做会出现另一个潜在问题:使用 getClass 的原因是为了确保 equals 契约的对称属性。 Java文档:
*It is symmetric: for any non-null reference values x and y, x.equals(y)
should return true if and only if y.equals(x) returns true.*
通过使用instanceof,有可能不对称。
示例:B 扩展 A。A 的 equals 对 A 进行实例化检查。B 的 equals 对 B 进行实例化检查。给出 A a 和 B b:
a.等于(b) --> true
b.equals(a) --> false
如何在不冒失去对称属性的风险的情况下用hibernate实现equals?看来我在使用 getClass 时不安全,并且在使用 instanceof 时也不安全?
答案是永远不要向子类添加重要成员,然后安全地使用instanceof(对于hibernate来说)?
我读到的资料来源:
在Java中重写equals和hashCode时应该考虑哪些问题? https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java
Josh Bloch 的优秀著作《Effective Java》中的第 7 条和第 8 条,http://web.archive.org/web/20110622072109/http://java.sun.com/developer/Books/ effectivejava/Chapter3.pdf http://web.archive.org/web/20110622072109/http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf
关于 Java 7:http://www.javacodegeeks.com/2012/11/guavas-objects-class-equals-hashcode-and-tostring.html http://www.javacodegeeks.com/2012/11/guavas-objects-class-equals-hashcode-and-tostring.html