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?
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).
Or as a generic method: