Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java guarantee that the Class object returned by getClass() will always be the same instance? [duplicate]

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?

like image 745
Adam Paynter Avatar asked Jan 24 '11 14:01

Adam Paynter


2 Answers

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.)

like image 54
biziclop Avatar answered Oct 04 '22 21:10

biziclop


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.

like image 39
PeterMmm Avatar answered Oct 04 '22 22:10

PeterMmm