As name suggests ClassCastException in Java comes when we try to type cast an object and object is not of the type we are trying to cast into. In fact ClassCastException in Java is one of most common exception in Java along with java.lang.OutOfMemoryError and ClassNotFoundException in Java before Generics was introduced in Java 5 to avoid frequent instances of java.lang.classcastexception cannot be cast to while working with Collection classes like ArrayList and HashMap, which were not type-safe before Java 5. Though we can minimize and avoid java.lang.ClassCastException in Java by using Generics and writing type-safe parameterized classes and method, its good to know real cause of ClassCastException and How to solve it. In this Java tutorial we will see Why java.lang.ClassCastException comes and how to resolve ClassCastException in Java. We will also see how to minimize or avoid ClassCastException in Java by using Generics, as prevention is always better than cure.
Cause of java.lang.ClassCastException in Java
In order to understand cause of ClassCastException, you need to be familiar with concept of type casting in Java. Since Java is an object oriented programming language and supports features like Inheritance and Polymorphism, a reference variable of type parent class can represent object of child class. This leads to ClassCastException if object is not of type on which you are casting it. It can be best explained with an example. Let's see a sample code which will throw ClassCastException in Java:
Above code will throw
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
If you see closely we were trying to cast an String object into an Integer object which is not correct and that’s why Java throws java.lang.classcastexception cannot be cast to error. Problems can become more difficult if all class are closely related. Since due to polymorphism in Java an Object instance can hold any type of Object but you can only cast between same type. what makes this problem worse is that it only comes during runtime, ClassCastException doesn't come at compile time which makes it hard to detect specially in large enterprise Java application or high frequency electronic trading system where input comes from upstream and in production various kinds of input are available. This was frequent problem with Java Collection classes like LinkedList and HashSet in Java which holds Object type but with introduction of Generics in Java 5 solved this problem by checking type-safety during compile time. Which means you can not store Integers on LinkedList of String, from Java 5 it will result in compile time error.
Common source of java.lang.ClassCastException
Following are some of the most common source of ClassCastExcepiton in Java:
1. Java Collection classes like HashMap, ArrayList, Vector or Hashtable which is not using Generics.
2. Methods which were written to take advantage of polymorphic behavior and coded on interfaces prior to Java 5 and doesn’t used parameter to provide type-safety.
look for all places where you have used cast operator in Java and verify that whether that code is type-safe or not.
How to fix java.lang.ClassCastException in Java
Solving ClassCastException can be very easy once you understand polymorphism in Java and difference between compile time and runtime things. ClassCastException are simple like NullPointerException just look the stack-trace and go to the line number. Many of advanced Java IDE like Eclipse and Netbeans will give you hyperlink to navigate till culprit line number in Java file. Now you know where exactly ClassCastException is coming and stack trace also told which object it was trying to cast, Now you have to find, how that type of object comes and this could take some time based upon complexity of your java application. You can also prevent ClassCastException in Java by using Generics. Generics are designed to write type-safe code and provides compile time checks which tends to violate type-safety. By using Generics in Collection classes and other places you can safely minimize java.lang.ClassCastException in Java.
That’s all on What is ClassCastException in Java and how to solve Exception in thread "main" java.lang.ClassCastException. I highly recommend to use Generics while using any Collection classes or class which acts as container e.g. ThreadLocal in Java. Also write your own classes and method to take advantage of Generics to provide type-safety as shown in this example of How to write parameterized class. It’s also a good idea to refresh your knowledge on type-casting in Java.
Other Java debugging and troubleshooting tutorials