首页 > 其他 > 详细

泛型实现原理:类型擦除

时间:2020-04-16 00:45:48      阅读:58      评论:0      收藏:0      [点我收藏+]

类型擦除

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!