在进行泛型转换时在泛型方法中捕获ClassCastException [英] Catching ClassCastException in a generic method when doing generic cast

查看:502
本文介绍了在进行泛型转换时在泛型方法中捕获ClassCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个方法

  @SuppressWarnings(unchecked)
public< T extends Number> T getNumber(){
尝试{
return(T)number;
} catch(ClassCastException e){
return null;


$ / code>

假设 number 是一个 Integer 的实例,调用方法如

  Float f = getNumber(); 

结果为 ClassCastException



我知道(某种程度上)这是因为类型擦除,但有人可以提供更深刻的解释,说明为什么异常升级到分配级别,而不是可捕获的内部方法?



注意:我的版本 public< T extends Number> T getNumber(Class classT)检查classT的类型,但希望避免传递 classT ,并停止对上述问题。

解决方案

类型擦除后, return(T)number return(Number)number (因为 Number T 是一个 Integer 的实例),它不会引发异常(因为 number p>

另一方面,赋值

  Float f = getNumber() ; 

被编译为

  Float f =(Float)getNumber(); 

getNumber()返回一个 Number ,不能将其分配给 Float 变量,而无需转换。

getNumber()不是 Float时,此cast会抛出 ClassCastException


4.6。类型擦除类型擦除是从类型(可能包括参数化类型和类型变量)到类型(从未参数化类型或类型变量)的映射。我们写| T |擦除映射的定义如下...

擦除一个类型变量(§4.4)是擦除其最左边界。



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.

解决方案

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.

4.6. Type Erasure

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.

这篇关于在进行泛型转换时在泛型方法中捕获ClassCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆