ygyz03 2012-03-12 22:26 采纳率: 0%
浏览 246
已采纳

请各位大师帮我分析一下这是为什么会出现如下的现象

[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会出现异常,求解释,谢谢大师。

  • 写回答

10条回答 默认 最新

  • _1_1_7_ 2012-03-14 08:13
    关注

    至于“类型擦除”:
    [code="java"] ArrayList collection2 = new ArrayList();

    collection2.getClass().getMethod("add", Object.class).invoke(collection2, 1);

    System.out.println(collection2.get(0));//ABC

    [/code]

    编译后相当于:
    [code="java"]
    ArrayList collection2 = new ArrayList(); //这里是擦除了
    collection2.getClass().getMethod("add", Object.class).invoke(collection2, 1);

    System.out.println((String)collection2.get(0));//因为 PrintStream有对应的println(String s)的方法,所以会有强制类型转化。

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺