Saturday, June 4, 2011

How to solve java.lang.ClassCastException?

java.lang.ClassCastException at...
You might get full exception stack trace of ClassCasteException. Before solving this problem we must know following information.

What is java.lang.ClassCastException ? Why do I get java.lang.ClassCastException?
This exception indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:
Object x = new Integer(0);
System.out.println((String)x);

Another example is, suppose you have set ArrayList into the request Object in Action, and you are retrieving Map object as below:
List a = new ArrayList();a.add("Biren");
request.setAttribute("data",a); //in servlet/action you set object of List
Map data = (Map)request.getAttribute("data"); // in jsp, you tried to store List object into Map object.
 or, here in jsp, you are trying to get date which is list type  and assign to map object.

So, to solve this problem, you must go through the code and find what kind of object you are setting, and store the object into same type.
If you are using Java 5, you can define type of object while creating object.
example:
List info = new ArrayList();
If you try to store int value into info, it will give you error at compile time,



Example:
In Servlet/Action
  
List a = new ArrayList();a.add("Biren");
request.setAttribute("data",a); //in servlet/action you set object of List

Class Cast Exception in jsp/other class:
Map data = (Map)request.getAttribute("data");

Correct approach:
 List a =(List)request.getAttribute("data");






No comments:

Post a Comment