Catching ClassCastException in a generic method when doing generic cast

后端 未结 1 1612
旧时难觅i
旧时难觅i 2021-01-15 05:17

Suppose I have a method

@SuppressWarnings(\"unchecked\")
public  T getNumber() {
   try {
      return (T)number; 
   } catch (ClassC         


        
相关标签:
1条回答
  • 2021-01-15 05:36

    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.

    0 讨论(0)
提交回复
热议问题