反射跳过泛型检查

 @Test
public void method() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
//创建集合
ArrayList<Integer> list = new ArrayList<>();
//通过对象获取字节码对象
Class<? extends ArrayList> aClass = list.getClass();
//反射获取add ()
Method method = aClass.getMethod("add", Object.class);
method.invoke(list,"mlj");
method.invoke(list, "qq");
method.invoke(list, 'h');
System.out.println(list);
//输出 [mlj, qq, h]

// 分析:反射直接跳过了泛型Integer,list存储String类型值;
// 结论:泛型只是给编译器看的,实际的单列集合,双列集合可以交叉存储任意引用值
}



 

猜你喜欢

转载自www.cnblogs.com/mljqqh/p/9691825.html
今日推荐