反射可以越过泛型的机制。
代码如下
package fanshe_test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
public class example {
public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
ArrayList<Integer> arry = new ArrayList<Integer>();
arry.add(10);
arry.add(20);
Class <?extends ArrayList> c=arry.getClass();
Method m =c.getMethod("add", Object.class);
m.invoke(arry, "hello");
System.out.println(arry);
}
}
结果如下:
[10, 20, hello]