泛型是JDK1.5 版本的新特性,泛型的好处是在编译时期编译器会检查你的类型,在编译完成以后就擦除掉泛型的信息.
阅读下面的Demo就可以理解了:
package com.mari.generic;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) throws Exception {
//创建一个ArrayList,指定的泛型为String类型
ArrayList<String> list = new ArrayList<String>();
调用add方法,往集合中插入一个字符串
list.add("abc");
//使用反射技术拿到add方法
Method method = ArrayList.class.getDeclaredMethod("add", Object.class);
method.setAccessible(true);
//调用add方法,往list集合中插入一个int类型的5.
method.invoke(list, 5);
//拿到list集合中的第二条数据.也就是我们插入的int类型的5
//这里就会抛出异常了.Integer不能转换为String类型.
System.out.println(list.get(1));
}
}
下面是Demo输出的结果:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at com.mari.generic.Main.main(Main.java:19)