Re: How to identify the cause of ClassCastException?
Daniel Pitts wrote:
There are two concepts for type that I think you're confusing...
Runtime type and Compile-time type.
You can not change the runtime type of an object once it has been
created (new State() creates a State instance), Casting *only* changes
the compile-type type information (what the compiler sees).
To state Daniel's point a little differently, in hopes that you can
triangulate on the concept, a variable has a compile-time type, and an object
itself has a run-time type. You can refer to an object via a variable of a
superclass (or super-interface) compile-time type.
Super something = new Sub();
For example,
List <String> data = new ArrayList <String> ();
List is a supertype of ArrayList. The object pointed to by the variable data
is still of type ArrayList, but the variable is of type List.
Now consider the inverse:
javax.management.AttributeList attributes = new ArrayList <Object> ():
Oops. You can't do that, because the object created by 'new' is a supertype
of AttributeList.
So therefore this will also fail:
ArrayList <Object> stuff = new ArrayList <Object> ();
javax.management.AttributeList attributes =
(javax.management.AttributeList) stuff;
Oops. Illegal cast.
<http://java.sun.com/javase/6/docs/api/javax/management/AttributeList.html>
<http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html>
--
Lew