views:

172

answers:

3

I really do mean identity-equality here.

For example, will the following always print true.

System.out.println("foo".getClass() == "fum".getClass());

Thanks in advance,

~Mack

+5  A: 

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.

Bozho
Another clue is that the javadoc says that `getClass` returns "_The_ Class object that represents the runtime class of this object" ... not "_A_ Class object ...".
Stephen C
+14  A: 

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.

Péter Török
+4  A: 

For two instances of class X,

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

only if

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

Note: getClassLoader() may return null in some implementations, which implies the system ClassLoader.

McDowell