什么是类型擦除?
类型参数只存在于编译期,在运行时,Java 的虚拟机并不知道泛型的存在。
示例:
import java.util.ArrayList;
public class ErasedTypeTest {
public static void main(String[] args) {
Class c1 = new ArrayList<String>().getClass();
Class c2 = new ArrayList<Integer>().getClass();
System.out.println(c1 == c2);//true,这里并不知道类ArrayList<String>和ArrayList<Integer>,只知道ArrayList
}
}
参考:
https://segmentfault.com/a/1190000020382440
https://segmentfault.com/a/1190000005179142
public void testMethod(List<Integer> array) {}
public void testMethod(List<Double> array) {} // compile error
static <T> void genericMethod(T t) {
T newInstance = new T(); // compile errror
Class c = T.class; // compile errror
List<T> list = new ArrayList<T>(); // compile errror
if (list instance List<Integer>) {} // compile errror
}
原文:https://www.cnblogs.com/JohnTeslaaa/p/12706786.html