Does Java guarantee that Object.getClass() == Object.getClass()? Does Java guarantee that Object.getClass() == Object.getClass()? java java

Does Java guarantee that Object.getClass() == Object.getClass()?


Yes, class tokens are unique (for any given classloader, that is).

I.e. you will always get a reference to the same physical object within the same classloader realm. However, a different classloader will load a different class token, in conjunction with the fact that the same class definition is deemed different when loaded by two distinct classloaders.

See this earlier answer of mine for a demonstration of this.


For two instances of class X,

x1.getClass() == x2.getClass()

only if

x1.getClass().getClassLoader() == x2.getClass().getClassLoader()

Note: Class.getClassLoader() may return null which implies the bootstrap ClassLoader.


Yes.

The returned Class object is the object that is locked by static synchronized methods of the represented class.

If it was possible to return multiple instances, then

public static synchronized void doSomething() {..}

would not be thread-safe.