【发布时间】:2013-01-25 23:32:40
【问题描述】:
在阅读(再次,很久以前应该这样做)正确实施equals和hashcode之后,我得出了这些结论,这对我有用:
如果在 JDK 7 之前:更喜欢使用 Apache commons equalsbuilder 和 hashcodebuilder。 (或番石榴)。 他们的 javadocs 包含如何以良好方式使用它们的示例。
如果 JDK 7++:使用新的 Objects 实用程序类
但是,如果为休眠编写会出现一些特殊要求(请参阅下面的来源) 其中推荐使用 instanceof 而不是 getClass,因为 hibernate 会创建延迟加载的子类代理。
但据我了解,如果这样做会出现另一个潜在问题:使用 getClass 的原因是为了确保 equals 合约的对称属性。 JavaDocs:
*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 进行 instanceof 检查。B 的 equals 对 B 进行 instanceof 检查。给 A a 和 B b:
a.equals(b) --> 真 b.equals(a) --> 错误
如何在不丢失对称属性的情况下使用 hibernate 实现 equals?用getClass好像不安全,用instanceof也不安全?
答案是永远不要向子类添加重要成员,然后安全地使用 instanceof(对于休眠)?
我阅读的来源:
What issues should be considered when overriding equals and hashCode in Java?
Josh Blochs 优秀著作《Effective Java》中的第 7 条和第 8 条,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
【问题讨论】:
标签: java hibernate java-7 hashcode instanceof