反射——通过反射越过泛型检查

一、目的

通过反射来越过泛型检查

二、应用场景

向 ArrayList <Integer> 中添加一个 字符串数据 

代码:

public static void main(String[] args) throws Exception, Exception {
		 ArrayList<Integer> arrayList = new ArrayList<>();
		 arrayList.add(1);
		 arrayList.add(2);
		 arrayList.add(3);
		 System.out.println(arrayList); // 输出:  [1, 2, 3]
		 
		 Class clazz = arrayList.getClass();
		 Method  m = clazz.getMethod("add",Object.class );
		 
		 m.invoke(arrayList, "String");
		 
		 System.out.println("反射后的结果:"+arrayList); //输出: 反射后的结果:[1, 2, 3, String]

三、原因

为什么,通过反射就可以越过泛型检查?

因为java类,在编译时期会对泛型进行检查。但是当类被转化为字节码文件( .class)时候(运行时期,没有泛型),泛型就被擦除了,也就没有了泛型检查。所以可以通过反射来越过泛型检查

猜你喜欢

转载自blog.csdn.net/qq_38214630/article/details/85264870