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
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.
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.
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.
// 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.
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);
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With