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
You are trying to treat an object as an instance of a class that it is not. It's roughly analogous to trying to press the damper pedal on a guitar (pianos have damper pedals, guitars don't).
It is an Exception which occurs if you attempt to downcast a class, but in fact the class is not of that type.
Consider this heirarchy:
You might have a method called:
If called with this code:
It will compile just fine, but at runtime you will get a
ClassCastException
because o was in fact an Animal, not a Dog.In later versions of Java you do get a compiler warning unless you do:
It's really pretty simple: if you are trying to typecast an object of class A into an object of class B, and they aren't compatible, you get a class cast exception.
Let's think of a collection of classes.
A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.
If you try to run this Java program you’ll see that it will throw the following ClassCastException:
The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.
If you want to sort objects but if class didn't implement Comparable or Comparator, then you will get ClassCastException For example
Above main method will throw below runtime class cast exception
Do you understand the concept of casting? Casting is the process of type conversion, which is in Java very common because its a statically typed language. Some examples:
Cast the String "1" to an int -> no problem
Cast the String "abc" to an int -> raises a ClassCastException
Or think of a class diagram with Animal.class, Dog.class and Cat.class