I understand that if an object does not explicitly override equals, it uses the base Object.equals() instead, which is effectively no different from the == operator.
Class<?> does not explicitly override equals, so my next question is, am I guaranteed that two Class<T> of the same will compare == with equals? Or, could one instance of a Class<T> that I declare be a different object reference than another one with the same type argument T?
In other words, is there any possibility with a conforming Java environment that the following code would output anything other than "true"?
public class ClassA
{
private static final String STRING = "Hello World";
public final Class<?> theClass = STRING.getClass();
public final Class<?> theClass2 = "Goodbye World".getClass();
public static void main(String[] args)
{
ClassA a = new ClassA();
System.out.println(Boolean.toString(a.theClass == a.theClass2));
}
}
Pretty safe.
From the Java Virtual Machine Specification § 5.3:
This means that while it is not guaranteed, you may assume that the classloader you're using adheres to that statement.
This of course assumes that each class is loaded by a single classloader. The model used by the JVM is that classloaders may delegate the loading of a class to another classloader. So while I cannot find exactly whether it's prohibited to load the same class by different classloaders, I cannot imagine, under normal circumstances, how the class instance on the left-hand side of the
==operator would be different than the instance on the right-hand side.