How do I catch ClassCastException?
I'm trying to catch a ClassCastException when deserializing an object from xml.
So,
try {
restoredItem = (T) decoder.readObject();
} catch (ClassCastException e){
//don't need to crash at this point,
//just let the user know that a wrong file has been passed.
}
And yet this won't as the exception doesn't get caught. What would you suggest?
Asked by: Walter892 | Posted: 21-01-2022
Answer 1
The code in the question should give you an unchecked cast warning. Listen to -Xlint.
All the compiler knows about T is its bounds, which it probably doesn't have (other than explicitly extending Object and a super of the null type). So effectively the cast at runtime is (Object) - not very useful.
What you can do is pass in an instance of the Class of the parameterised type (assuming it isn't generic).
class MyReader<T> {
private final Class<T> clazz;
MyReader(Class<T> clazz) {
if (clazz == null) {
throw new NullPointerException();
}
this.clazz = clazz;
}
public T restore(String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
return restoredItem;
} catch (ClassCastException exc) {
...
}
}
}
Or as a generic method:
public <T> T restore(Class<T> clazz, String from) {
...
try {
restoredItem = clazz.cast(decoder.readObject());
...
Answered by: Steven762 | Posted: 22-02-2022
Answer 2
There will not be any ClassCastException, except when your T has some base:
public class GenericsTest
{
public static void main(String[] args)
{
System.out.println(cast(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> cast(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> cast("Hallo"));
System.out.println(castBaseNumber(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> castBaseNumber(Integer.valueOf(0)));
System.out.println(GenericsTest.<Long> castBaseNumber("Hallo"));
}
private static <T extends Number> T castBaseNumber(Object o)
{
T t = (T)o;
return t;
}
private static <T> T cast(Object o)
{
T t = (T)o;
return t;
}
}
In the above example, there will be no ClassCastException in the first 5 calls to cast and castBaseNumber. Only the 6th call throws a ClassCastException, because the compiler effectively translates the cast() to return (Object) o and the castBaseNumber() to return (Number)o;. Wenn you write
String s = GenericsTest.<Long> cast("Hallo");
You would get a ClassCastException, but not whithin the cast-method, but at the assignment to s.
Therefore I do think, your "T" is not just "T", but "T extends Something". So you could check:
Object o = decoder.readObject();
if (o instanceof Something)
restoredItem = (T) o;
else
// Error handling
But this will still lead to an error later, when the you use your class.
public Reader<T extends Number>{...}
Long l = new Reader<Long>("file.xml").getValue(); // there might be the ClassCastException
For this case only Tom's advise might help.
Answered by: Elise348 | Posted: 22-02-2022Answer 3
Well, I can't use instanceof
operator as the method is a parametrized one:
public T restore(String from){
...
restoredItem = (T) decoder.readObject();
...
}
And generics in Java are compile-time only.
Answered by: Elian822 | Posted: 22-02-2022Answer 4
If you can't use instaceof you might be able to use the isAssignableFrom method on Class
Answered by: Lenny825 | Posted: 22-02-2022Similar questions
java - Intermittent ClassCastException from ElementNSImpl to own type during unmarshalling
We are experiencing an exceedingly hard to track down issue where we are seeing ClassCastExceptions sometimes when trying to iterate over a list of unmarshalled objects. The important bit is sometimes, after a reboot the particular code works fine. This seems to point in the direction of concurrency/timing/race condition. I can confirm that neither the JAXBContext, nor the marshallers and unmarshallers ar...
java - Strange ClassCastException
This:
Timerange longest = Timerange.longest(breaks);
if (longest.durationInHours() >= MIN_FREE_HOURS)
return true;
is OK.
But this:
if (Timerange.longest(breaks).durationInHours() >= MIN_FREE_HOURS)
return true;
gives:
java.lang.ClassCastException
Do you know why?!
For simplic...
java - Unknown source of ClassCastException (in JTables)
I'm presently refactoring a JTable which displays a multitude of different types of data. The primary reason for this refactoring is that there a few ClassCastExceptions (the author/friend who wrote the code is off on hiatus), and I can't seem to find where these are originating from. Due to the large codebase, I'm at a loss as to where to start. Does anyone have any suggestions? I realize and apo...
java - Why is this code throwing a ClassCastException and how to avoid it
Consider this code:
import java.util.*;
class jm45 implements Comparator<jm45>
{
private int x;
jm45(int input) { x = input; }
public static void main( String args[] )
{
List list = new ArrayList();
list.add(new jm45(2));
list.add(new jm45(2));
Collections.sort(list); //faulty line
}
public int compare( jm45 t1 , jm45 t2 )
{
return t1.x - t2.x;
...
java - OSGi in Netbeans, ClassCastException when retrieving service
im having a ClassLoader issue.
Since im quite an osgi newby, hopefully the answer isn't that hard :)
I think it has to do with Compile vs. Runtime libraries.
in Netbeans 6.7.1 project properties, the compiletime libs are always propagated to the other categories.. so i can't differentiate there.
When compiling the FelixHost the next jars are used
Felix.jar
osgi-core.jar...
classcastexception - isAssignableFrom function of Class.java
I am trying following
Context ctx = (Context) jndiCntx.lookup(fSTANDARD_ENVIRONMENT);
Object obj = ctx.lookup(fSTANDARD_JNDINAME);
And following code is returning me false
MyClass.class.isAssignableFrom(obj.getClass())
although
MyClass.class.getName().equalsIgnoreCase(obj.getClass().getName()) returns true.
I am not able to cast obj to MyClass as it throws ClassCast...
java - Why does ClassCastException not show the class name?
In Java 1.4.2 and earlier versions, if you get a ClassCastException, you can see the exception stack trace but not the class name. If you want to find out the class of the object for which casting failed, you have to debug.
Is it still the same in later Java versions? If so, when did it change?
java - ClassCastException when casting object Array to Long array
I get this exception when i try to cast an Object array to a Long array.
Exception in thread "main"
java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to
[Ljava.lang.Long;
My keys in my hotelRooms map are Long, why it is not possible to cast. Does someone know how to solve this.
public class ObjectArrayToLongArrayTest {
private Map<Long,...
java - Why am I getting this ClassCastException?
I have two very simple classes, one extends the other:
public class LocationType implements Parcelable {
protected int locid = -1;
protected String desc = "";
protected String dir = "";
protected double lat = -1000;
protected double lng = -1000;
public LocationType() {}
public int getLocid() {
return locid;
}
public void setLocid(int value) {
...
java - ClassCastException when using HQL
See the following mapping
public class SomeClass {
private Integer someField;
}
When i call the following query
select someField, count(*) from SomeClass inner join OtherClass... group by ...
And i proccess the query as follows
Map<Integer, Integer> result = new HashMap<Integer, Integer>();
List<Object> objectList =...
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)