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.)
That really depends on the class loader and as i understand is not guaranted:
http://java.sun.com/docs/books/jls/second_edition/html/execution.doc.html#44459
Well-behaved class loaders maintain these properties:
- Given the same name, a good class loader should always return the same class object.
- If a class loader L1 delegates loading of a class C to another loader L2, then for any type T that occurs as the direct superclass or a direct superinterface of C, or as the type of a field in C, or as the type of a formal parameter of a method or constructor in C, or as a return type of a method in C, L1 and L2 should return the same class object.
A malicious class loader could violate these properties. However, it could not undermine the security of the type system, because the Java virtual machine guards against this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With