Class A is not equals Class A
We do have a cache (Map
) with objects of Class TestClass
. Another classloader initializes/loads TestClass
at runtime again, so below code will threw a ClassCastException
:
TestClass obj1 = (TestClass)map.get("key"); // throws a ClassCastExce开发者_Go百科ption
ClassCastException when casting to the same class
Alright, I do understand this issue up to this point.
So, I was trying to find background information why is TestClass.class
not equals TestClass.class
. I assume that the different classloader set a different id to the ReferenceType? Anyone able to explain the background to me?
Best page I've found: http://www.objectsource.com/j2eechapters/Ch21-ClassLoaders_and_J2EE.htm
Yes, your research points to the right direction: the same class definition loaded by different class loaders is seen as two distinct classes by the JVM. Thus casting between them fails with ClassCastException
.
I think the difference is simply because there are two distinct class token objects in play. It has to be like this, since the classes loaded by the different loaders may in fact be different versions of the same class. It is known that the class token for every class is unique (within the same classloader realm, that is). It would open up a can of worms if the JVM started to compare class tokens by their various attributes, rather than by physical equality (==
).
What you experienced is the reason why custom class loaders exist. They allow to load different class with the same name in one JVM. The identity of a class in a JVM is given by the tuple consisting of the class name and the class loader. In the language Java a class is identified just by fully qualified name.
Anyone able to explain the background to me?
As Péter Török already explained they are considered different when loaded from different classloaders. The background is that an application server should be able to support different versions of an application e.g. different versions of the same libraries included in your ear-files.
There is no mystery. Runtime equality of types is defined in the Java Language Specification as follows:
"At run time, several reference types with the same binary name may be loaded simultaneously by different class loaders. These types may or may not represent the same type declaration. Even if two such types do represent the same type declaration, they are considered distinct."
JLS 4.3.4 - When reference types are the same. (2nd paragraph)
精彩评论