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

时间:2022-03-13 08:16:42

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

源码:

package com.srie.testjava;

public class TestClassDefine4<T> {

    public static void main(String[] args) {
TestClassDefine4<String> t4 = new TestClassDefine4<String>();
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<T>
{
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)