通过反射绕过编译向泛型为String的ArrayList里面添加整型

来源:互联网 发布:中衡设计怎么样 知乎 编辑:程序博客网 时间:2024/06/05 04:08

反射的操作都是在编译后,在运行的时候,java中集合的泛型是防止错误输入的,

只在编译阶段有效,绕过编译就无效了,编译之后泛型是去泛型化的,利用这一点可以向范型为String的ArrayList里面添加整型

新建ReflectDemo.java

package com.imooc.io;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;public class ReflectDemo {public static void main(String[] args){ArrayList list = new ArrayList();ArrayList<String> list2 = new ArrayList<String>();list2.add("hello");//由于list2是范型,只能添加String的类型,以下是错误的//list2.add(20);/* * c1==c2结果返回true说明编译之后集合的泛型是去泛型化的 * Java中集合的泛型,是防止错误输入的,只在编译阶段有效, * 绕过编译就无效了 * 验证:我们可以通过方法的反射来操作,绕过编译 */Class c1 = list.getClass();Class c2 = list2.getClass();System.out.println(c1==c2);try {Method M = c2.getMethod("add", Object.class);M.invoke(list2, 20);System.out.println(list2.size());System.out.println(list2);//现在不能这样遍历,里面添加了整型/*for (String string : list1) {System.out.println(string);      }*/} catch (NoSuchMethodException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (IllegalArgumentException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}}

运行结果:

true
2
[hello, 20]

0 0
原创粉丝点击