Possible Duplicate:
Does Java guarantee that Object.getClass() == Object.getClass()?
I noticed that Eclipse generates this code for equals:
public class MyClass {
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyClass other = (MyClass) obj;
// ...
}
}
Of particular interest is this code:
if (getClass() != obj.getClass())
return false;
The code assumes that the Class object returned by getClass() will be the same instance (not just an equivalent instance) for all objects of the same class. That is, they didn’t deem it necessary to write it like this:
if (getClass().equals(obj.getClass()))
return false;
Does Java officially document this behavior of the getClass() method?
Yes, the class object will be the same so long as the two classes were loaded by the same classloader.
But if they weren’t, the two classes have to be regarded as different, even though they may share the same name and code. (This is something that can easily be run into when using multiple classloaders, so it’s worth remembering.)