ArrayList<Integer> arr1 = new ArrayList<Integer>();
arr1.getClass().getMethod("add", Object.class).invoke(arr1, "abc");
System.out.println(arr1.get(0));
上面这个没有问题,可以把泛型屏蔽掉,但是下面的却不行:
ArrayList<String> arr2 = new ArrayList<String>();
arr2.getClass().getMethod("add", Object.class).invoke(arr2, 2);
System.out.println(arr2.get(0));
运行报了异常:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
at day1.GenericTest.main(GenericTest.java:30)