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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…