Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException

Tags:

java

Normally whats the reason to get java.lang.ClassCastException ..? I get the following error in my application

java.lang.ClassCastException: [Lcom.rsa.authagent.authapi.realmstat.AUTHw 
like image 601
selvam Avatar asked Aug 18 '10 10:08

selvam


People also ask

How do I resolve Java Lang ClassCastException error?

To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

What is Java Lang ClassCastException?

ClassCastException is a runtime exception raised in Java when we try to improperly cast a class from one type to another. It's thrown to indicate that the code has attempted to cast an object to a related class, but of which it is not an instance.

What is ClassCastException in Java with example?

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. So, for example, when one tries to cast an Integer to a String , String is not an subclass of Integer , so a ClassCastException will be thrown.

How do you resolve a Classcast exception?

// type cast an parent type to its child type. In order to deal with ClassCastException be careful that when you're trying to typecast an object of a class into another class ensure that the new type belongs to one of its parent classes or do not try to typecast a parent object to its child type.


2 Answers

According to the documentation:

Thrown to 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);  
like image 171
Laurențiu Dascălu Avatar answered Oct 06 '22 16:10

Laurențiu Dascălu


A ClassCastException ocurrs when you try to cast an instance of an Object to a type that it is not. Casting only works when the casted object follows an "is a" relationship to the type you are trying to cast to. For Example

Apple myApple = new Apple(); Fruit myFruit = (Fruit)myApple; 

This works because an apple 'is a' fruit. However if we reverse this.

Fruit myFruit = new Fruit(); Apple myApple = (Apple)myFruit; 

This will throw a ClasCastException because a Fruit is not (always) an Apple.

It is good practice to guard any explicit casts with an instanceof check first:

if (myApple instanceof Fruit) {   Fruit myFruit = (Fruit)myApple; } 
like image 29
mR_fr0g Avatar answered Oct 06 '22 17:10

mR_fr0g