泛型实现原理:类型擦除

类型擦除

什么是类型擦除?
类型参数只存在于编译期,在运行时,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
}

猜你喜欢

转载自www.cnblogs.com/JohnTeslaaa/p/12706786.html