Suppose I have a method
@SuppressWarnings("unchecked")
public <T extends Number> T getNumber() {
try {
return (T)number;
} catch (ClassCastException e) {
return null;
}
}
Assuming number
is an instance of Integer
, invoking method like
Float f = getNumber();
results into a ClassCastException
.
I know (somehow) that this is because of type erasure but could someone provide more profound explanation why the exception escalates up to the assignment level and is not catchable inside method?
NOTE: I do have the version public <T extends Number> T getNumber(Class<T> classT)
that checks the type from classT but was hoping to get rid of passing the classT
and stopped wondering the above problem.
<T>
only it would bereturn (Object)number
? – Nonce