I read some articles written on "ClassCastException", but I couldn't get a good idea on that. Is there a good article or what would be a brief explanation?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
A very good example that I can give you for classcastException in Java is while using "Collection"
This above code will give you ClassCastException on runtime. Because you are trying to cast Integer to String, that will throw the exception.
You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.
But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.
Straight from the API Specifications for the
ClassCastException
:So, for example, when one tries to cast an
Integer
to aString
,String
is not an subclass ofInteger
, so aClassCastException
will be thrown.A class cast exception is thrown by Java when you try to cast an Object of one data type to another.
Java allows us to cast variables of one type to another as long as the casting happens between compatible data types.
For example you can cast a String as an Object and similarly an Object that contains String values can be cast to a String.
Example
Let us assume we have an HashMap that holds a number of ArrayList objects.
If we write code like this:
it would throw a class cast exception, because the value returned by the get method of the hash map would be an Array list, but we are trying to cast it to a String. This would cause the exception.
Consider an example,
At
Another t5 = (Another) new Goat()
: you will get aClassCastException
because you cannot create an instance of theAnother
class usingGoat
.Note: The conversion is valid only in cases where a class extends a parent class and the child class is casted to its parent class.
How to deal with the
ClassCastException
:Source of the Note and the Rest