Search code examples
javaclassequals

In Java, am I safe to assume that `==` will work to compare objects of type `Class<?>`?


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));
    }
}

Solution

  • Pretty safe.

    From the Java Virtual Machine Specification § 5.3:

    well-behaved class loader should maintain three properties:

    Given the same name, a good class loader should always return the same Class object.

    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.