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 = "旺财";
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));
}
}
}这道题很简单的,首先要知道泛型技术是编译时期的技术,在编译通过后,生成的类文件里面没有泛型的。 我们跳过编译,用反射调用生成的类文件,中的方法,用里面的方法添加string类型的就ok了。这样就跳过泛型了。
就两个知识点:反型 + 反射
|