| Author |
ClassCastException
|
Srikkanth Mohanasundaram
Ranch Hand
Joined: Feb 07, 2007
Posts: 185
|
|
Hi all, Most of the time my code breaks it is due to some or other ClassCastException,any precautions i should take?
|
 |
Sidd Kulk
Ranch Hand
Joined: Feb 20, 2007
Posts: 152
|
|
ClassCastException generally creeps in when you try to cast an object of one type into another incompatible type. For e.g. When you say String s = (String)(an object of StringBuffer); The above will throw a ClassCastException. But if an object is a type of the casted object, then it doesn't throw this exception. e.g. // this will not throw the exception Object o = (Object)(any kind of object); To avoid this kind of Exception, you may use the instanceOf operator to check whether your object is castable into a particular type. Sid [ May 16, 2007: Message edited by: Sidd Kulk ]
|
 |
Srikkanth Mohanasundaram
Ranch Hand
Joined: Feb 07, 2007
Posts: 185
|
|
Hi, Thanks for your reply Regards, Srikkanth.M
|
 |
jayalal jayarathna
Greenhorn
Joined: May 17, 2007
Posts: 4
|
|
If U want to know what is the exact class of a given objet (ob), ob.getClass() will tell U the class name
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32644
|
|
Class casting is notoriously error-prone. Avoid it like the plague. In Java 5 and more recent you use generics; you can specify what kind of object is allowed into a collection etc, and there is no need for class casts in the first place.
|
 |
Ricky Clarkson
Ranch Hand
Joined: Jul 27, 2006
Posts: 131
|
|
|
Casting is for magicians, not programmers. Stop casting, and you'll stop getting exceptions from casts.
|
 |
 |
|
|
subject: ClassCastException
|
|
|