package cn.itcast.collection;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
//在这个泛型为Integer的ArrayList中存放一个String类型的对象。
public class reflectDemo {
//思路: 用反射跳过泛型,调用 ArrayList类中的add方法添加string
public static void main(String[] args) throws SecurityException, NoSuchMethodException, Exception, IllegalAccessException, InvocationTargetException {
ArrayList<Integer> al = new ArrayList<Integer>();
String str = "xiaomig";
Method m = al.getClass().getMethod("add", Object.class);// 得到add方法对象
m.invoke(al, str);
for(int x=0;x<al.size();x++){
System.out.println(al.get(x));
}
}
} |