Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Wiki Markup
In a Java Virtual Machine (JVM), "Two classes are the same class (and consequently the same type) if they are loaded by the same class loader and they have the same fully qualified name" \[[JVMSpec 1999|AA. Bibliography#JVMSpec 99]\]. A class with the same name but a different package name is different, and a class with the same fully qualified name but which has been loaded by a different class loader is also different.

Sometimes it is desirable It may be necessary to check whether a given object has a specific class type or whether two objects have the same class type associated with them, for example, when implementing the equals() method. If the comparison is performed incorrectly, the code might assume that the two objects are of the same class when they are not.

...

Conversely, the assumption that two classes deriving from the same codebase code base are themselves the same is error-prone. While this assumption is commonly observed to be true in desktop applications, it is typically not the case with J2EE servlet containers. The containers may use different class loader instances to deploy and recall applications at runtime, without having to restart the JVM. In such situations, two objects whose classes come from the same codebase code base may appear to the JVM to be two different classes. Also note that the equals() method may not return true when comparing objects originating from the same codebasecode base.

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
 // Determine whether object auth has required/expected class name
if (auth.getClass().getName().equals("com.application.auth.DefaultAuthenticationHandler")) {
  // ...
}

Multiple classes with identical names may exist with the same name in the JVM; consequently this is not a valid comparison.

...

The call to loadClass() returns the class having the specified name in the current namespace name space (consisting of the class name and the defining classloader), and the comparison is correctly performed on the two class objects.

...