在阅读之后(再次,应该已经做了很久以前)正确实现equals和hashcode我得出了这些结论,这对我有用:
如果在JDK 7之前:首选使用Apache commons equalsbuilder和hashcodebuilder.(或番石榴).他们的javadoc包含如何以良好方式使用它们的示例.
如果是JDK 7 ++:使用新的Objects实用程序类
但是,如果为hibernate编写一些特殊的请求出现(参见更远的源代码)其中推荐使用instanceof而不是getClass,因为hibernate创建了延迟加载的子类的代理.
但据我所知,如果这样做又发生了另一个潜在的问题:使用getClass的原因是为了确保equals合约的对称属性.JavaDoc中:
*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.*
Run Code Online (Sandbox Code Playgroud)
通过使用instanceof,它可能不是对称的.示例:B扩展A. A的等于A的检查实例.B的等于B的实例检查.给A a和B b:
a.equals(b) - > true b.equals(a) - > false
如何实现与hibernate相等而不会失去对称属性的风险?使用getClass时我似乎不安全,使用instanceof时我不安全?
答案是永远不要将重要成员添加到子类,然后使用instanceof是安全的(对于hibernate)?
我读到的消息来源:
在Java中覆盖equals和hashCode时应该考虑哪些问题?
Josh Blochs的第7和第8项优秀书籍"Effective Java",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