class中的泛型为什么不会擦除 为什么还能通过new Instance创造出各种不同类型,不是运行时就擦除了吗。
比如class<Father>,擦除后变class,那我new Instance他怎么知道我要new一个Father对象呢?
###强制类型转换了解下。
Class<Father> tClass = Father.class;
Father father = tClass.newInstance();
//编译后等同于
Class tClass = Father.class;
Father father = (Father)tClass.newInstance();
jvm并不知道tClass
是啥,你要Father
实例那就在tClass
实例化后强转成Father
给你了。
而泛型的意义就是保证这种强转没有问题。tClass
必定是Father.class
,不是的话,编译不通过的。所以可以肆无忌惮的强转了。
比如 ArrayList<Integer>
,擦除后变ArrayList
,那我get(0)
怎么知道我要一个Integer
对象呢?