java 泛型 捕获转换,在进行泛型转换时在泛型方法中捕获ClassCastException

Suppose I have a method

@SuppressWarnings("unchecked")

public 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 getNumber(Class classT) that checks the type from classT but was hoping to get rid of passing the classT and stopped wondering the above problem.

解决方案

After type erasure, return (T)number becomes return (Number)number (since Number is the type bound of T), which doesn't throw an exception (since number is an instance of Integer).

On the other hand, the assignment

Float f = getNumber();

is compiled to

Float f = (Float) getNumber();

since getNumber() returns a Number, which can't be assigned to a Float variable without a cast.

This cast throws the ClassCastException when getNumber() is not a Float.

Type erasure is a mapping from types (possibly including parameterized types and type variables) to types (that are never parameterized types or type variables). We write |T| for the erasure of type T. The erasure mapping is defined as follows...

The erasure of a type variable (§4.4) is the erasure of its leftmost bound.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值