tags:

views:

1215

answers:

4

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?

+4  A: 
Michael Myers
What the hell has markdown done to your reference?
Paul Tomblin
Hmm... I went and stripped out all links from the second part, but I don't know what's wrong with the first part.
Michael Myers
If anybody knows why the link is acting weird, please go ahead and fix it!
Michael Myers
Maybe it doesn't like anchor tags?
Paul Tomblin
But there aren't any anchor tags; I stripped them all out already.
Michael Myers
+2  A: 

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.

erickson
+2  A: 

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"
+3  A: 

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

djna
"You should be able to dump not only the type hierarchy but also the identity of the classloader for each class." How do you implement this?
James McMahon
This is a good suggestion, however after running .getClassLoader() on them both classes appear to be loaded by the same class loader.
James McMahon
Just for other folks who may be troubleshooting, there is more about the class loader issue at http://stackoverflow.com/questions/826319/classcastexception-when-casting-to-the-same-class.
James McMahon