Friday Java Quiz: Object Identity
Kevin IM-ed me yesterday with the following question:
How come foo.getBar() == expectedBar is true yet foo.getBar().equals(expectedBar) is false?
I'll make that today's Java quiz: Have you encountered a situation in non-play code where obj1 == obj2 is true yet obj1.equals(obj2) is false?
By non-play code I mean a code base where all equals() and hashCode() overrides honor their contracts. In other words, there are no silly code like
public boolean equals(Object other) {
return false;
}
Separate class proxies considered harmful
This can happen if you create a *separate* proxy out of a concrete class and the proxied equals method accesses fields. I think both Spring and Hibernate do this. Technically, the user's equals method abides by the contract, but evil
frameworks can break it. Note that making the proxy and your object the same instance (like Guice does) doesn't have this problem, nor does proxying interfaces.
Re: Friday Java Quiz: Object Identity
It's quite common to start equals() with checking the class membership, e.g.,
if(!otherObject instanceof MyClass) {return false;}.
This becomes problematic if MyClass is loaded by sibling class loaders (such as, two Web apps) and the call is made across the classloader boundary.