我们看一下下面的代码:
package com.example.Reflect;
import java.util.ArrayList;
public class MethodDemo2 {
public static void main(String[] args) {
ArrayList<Integer> list1 = new ArrayList<Integer>();
ArrayList<String> list2 = new ArrayList<String>();
Class c1 = list1.getClass();
Class c2 = list2.getClass();
System.out.println(c1 == c2);
}
}
上面的代码是一个简单集合的使用,其中list1的泛型是Integer,表示只能向里面加Integer的对象,list2的泛型是String,表示只能向里面加String的对象。而我们会发现c1 == c2却为true,表示说反射的操作都是编译之后的操作,编译之后集合的泛型是去泛型化,也就是在运行的时候集合是没有泛型的。这时候我们可以得到一个结论:Java中集合的泛型,是防止错误输入的,只在编译阶段有效,绕过编译就无效了。
我们可以通过方法的反射来操作,绕过编译
try {
System.out.println(list1.size());
Method method = c1.getMethod("add", Object.class);
method.invoke(list1, "12234");
System.out.println(list1.size());
} catch (NoSuchMethodException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}