Java泛型类型擦除导致的类型转换问题

初步结论:泛型类型转换不靠谱;

源码:

package com.srie.testjava;

public class TestClassDefine4 {

    public static void main(String[] args) {
        TestClassDefine4 t4 = new TestClassDefine4();
        String cast = t4.badCast(1);
        System.out.println(cast);
    }

    T badCast(Integer i) {
        return (T) i; // 此处有warning
    }
}

 

反编译:

package com.srie.testjava;

import java.io.PrintStream;

public class TestClassDefine4
{
  public static void main(String[] args)
  {
    TestClassDefine4 t4 = new TestClassDefine4();
    String cast = (String)t4.badCast(Integer.valueOf(1));
    System.out.println(cast);
  }

  T badCast(Integer i) {
    return i;
  }
}

 

运行异常:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
    at com.srie.testjava.TestClassDefine4.main(TestClassDefine4.java:7)

 

你可能感兴趣的:(Java泛型类型擦除导致的类型转换问题)