Re: How to identify the cause of ClassCastException?
I have two classes: State and WarmState.
public class State
{
... //many fields
}
public class WarmState extends State
{
... //more fields
}
Now, I have a State reference state, whose corresponding object was
created and filled. I believe/guess/thought it is a WarmState object.
Why did you guess? In general, you should keep the specific type if you
need it to be specific, so you can't make this mistake. If you need something
that may or may not be a WarmState, then checking with the instanceof operator
before the cast is a good idea. Or use the Visitor pattern
(http://en.wikipedia.org/wiki/Visitor_pattern) to dispatch to the
subclass-specific handler.
Now I need to pass state to a method which only take WarmState
parameter. So I cast state to WarmState type. But I ran into
ClassCastException. Like I said, state was created and loaded from a xml
file. I hope to find out what caused ClassCastException. But neither of
these gave me a clue:
In jdk1.5 and newer (maybe jdk1.4, I can't remember), the message for the
ClassCastException should include the type of the object on which the cast
was attempted. Older versions didn't, and you have to put it under a debugger
or add debugging code.
e.getMessage()
If this doesn't give you something like: "your.package.State", you're running
an old VM, or something else is strange.
The following code:
public class ClassCast {
public static void main(String[] args) throws Exception {
Object o = new Object();
try {
System.out.println((String)o);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
shows this for me:
[dagon tmp]$ java -version
java version "1.5.0_12"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_12-b04)
Java HotSpot(TM) Server VM (build 1.5.0_12-b04, mixed mode)
[dagon tmp]$ java -cp . ClassCast
java.lang.Object
--
Mark Rafn dagon@dagon.net <http://www.dagon.net/>