思路:泛型只在编译期有效,在运行期会被擦除掉,运行期间获取Class,反射执行add方法。
public class Demo006 {
/**
* @param args
* ArrayList<Integer>的一个对象,在这个集合中添加一个字符串数据,如何实现呢?
* 泛型只在编译期有效,在运行期会被擦除掉
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(111);
list.add(222);
Class<?> clazz = Class.forName("java.util.ArrayList");
Method method = clazz.getMethod("add", Object.class);
method.invoke(list, "abc");
System.out.println(list);
}
}