[code="java"]
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
public class BaiduDemo05 {
public static void main(String[] args) throws NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
ArrayList<Integer> collection1 = new ArrayList<Integer>();
collection1.getClass().getMethod("add", Object.class).invoke(collection1, "abc");
System.out.println(collection1.get(0));//ABC
ArrayList<String> collection2 = new ArrayList<String>();
collection2.getClass().getMethod("add", Object.class).invoke(collection2, "abc");
System.out.println(collection2.get(0));//ABC
ArrayList collection22 = new ArrayList();
collection22.getClass().getMethod("add", Object.class).invoke(collection22, "abc");
System.out.println(collection22.get(0));//ABC
ArrayList<Long> collection3 = new ArrayList<Long>();
collection3.getClass().getMethod("add", Object.class).invoke(collection3, "abc");
System.out.println(collection3.get(0));//ABC
ArrayList<Date> collection4 = new ArrayList<Date>();
collection4.getClass().getMethod("add", Object.class).invoke(collection4, 1);
System.out.println(collection4.get(0));//ABC
}
}
[/code]
但是在将abc替换为1时,只有第2个,也就是collection2会出现异常,求解释,谢谢大师。