昨天刚刚回顾了一下曾经了解过但是还是不懂的反射,看到了一个有意思的代码,如何在泛型为Integer的ArrayList中添加一个String类型的数据呢?
private void addStringToIntList() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
ArrayList<Integer> list = new ArrayList<>();
//使用反射获取list的add方法
Method method = list.getClass().getMethod("add", Object.class);
//将这个字符串添加进入list集合中
method.invoke(list, "Java反射机制实例。");
//打印出list中的数据,只有一条,因为我们只添加了一条
LogSystem.print(list.get(0));
}
运行结果是正常的,打印出了正常的数据,可是这是为什么呢?
搜索了一些资料:
因为泛型的作用层在编译时,而在运行时泛型会被擦除(这里我也不知道为什么),而反射在运行时获取到list的add方法,直接在运行时添加了数据,跳过了编译期。