I am trying to debug an issue involving a ClassCastException in Java. In the interest of solving the issue I need to know what is going on when I cast from Object to a specific type. Can anyone explain to me how the Java cast operator works at the Java level and the JVM level?
Other useful and authoritative references are found in the Java Virtual Machine Specification, specifically §2.6.5, "Narrowing Reference Conversions", and especially the definition of the checkcast
instruction.
Casting asserts that the runtime type of an object is compatible with the given static type, and thus allows you to call methods of that type on the object.
Here obj is a Integer object, but only accessible though an Object reference:
Object obj = new Integer(1);
Casting lets you treat it as an Integer (or some superclass of Integer) again:
System.out.println(((Integer) obj).intValue());
ClassCastException occours when the static type given does not match the runtime type of the object:
System.out.println(((Float) obj).intValue()); // runtime error
You can find the runtime type of any object by using getClass() and the various Class methods:
System.out.println(obj.getClass()); // prints "class java.lang.Integer"
A likely cause of class cast mystifcation is that not only do the types have to match but also they must be loaded by the same classloader.
You should be able to dump not only the type hierarchy but also the identity of the classloader for each class.
These kind of problems are not uncommon in appserver-style environments where application code and infratructure code are deliberately isolated - for example if system classes are accidentally included in applciation JARs you can have two copies of the "same" class inthe JVM and life gets confusing