Class A is not equal to Class A

We have a cache ( Map) with class objects TestClass. Another classloader initializes / loads TestClassat runtime again, so below code will throw ClassCastException:

TestClass obj1 = (TestClass)map.get("key"); // throws a ClassCastException

ClassCastException when running in a single class

Ok, I understand this problem up to this point.

So, I tried to find the source information, why TestClass.classnot equal TestClass.class. I assume that different class loaders set a different identifier in ReferenceType? Can anyone explain this background to me?

The best page I found: http://www.objectsource.com/j2eechapters/Ch21-ClassLoaders_and_J2EE.htm

+5
source share
4 answers

Yes, your research points in the right direction: the same class definition loaded by different class loaders is considered by the JVM as two different classes. So casting between the two fails with ClassCastException.

I think the difference is simply because the game has two different classes of tokens. This should be so, since classes loaded by different loaders can be different versions of the same class. It is known that a class token for each class is unique (within the same loadload class as it is). It will open a can of worms if the JVM starts comparing class tokens by their various attributes, and not by physical equality ( ==).

+8
source

, , , . JVM . JVM , . Java .

+1

- ?

, . , , . , .

+1

. Runtime Java :

"At run time, multiple reference types with the same binary name may be loaded by different class loaders at the same time. These types may or may not represent the same type declaration. Even if two such types represent the same type declaration, they are considered excellent. "

JLS 4.3.4 - When the reference types are the same . (2nd paragraph)

+1
source

All Articles