本帖最后由 杨增坤 于 2013-9-3 11:03 编辑
- public class GenericsDemo {
- public static void main(String[] args) throws Exception {
- ArrayList<Integer> al1=new ArrayList<Integer>();
- ArrayList<String> al2=new ArrayList<String>();
- System.out.println(al1.getClass() == al2.getClass());
-
- al1.getClass().getMethod("add", Object.class).invoke(al1, "abc");
- System.out.println(al1.get(0));
-
- al2.getClass().getMethod("add", Object.class).invoke(al2, 3);
- System.out.println(al2.get(0));
- }
- }
复制代码以上代码编译没有问题,运行结果如下,第三个打印出错是为什么呢? 运行结果:true abc Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at day16.GenericsDemo.main(GenericsDemo.java:16)
|