A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© zl78365336 中级黑马   /  2013-12-3 13:41  /  1185 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 zl78365336 于 2013-12-3 15:52 编辑

  1. 为何这个不可以
  2. java.lang.Integer cannot be cast to java.lang.String


  3. ArrayList<Integer> list=new ArrayList<Integer>();
  4. Method method=list.getClass().getMethod("add",Object.class);
  5. String str= "添加字符串!";                 //创建字符串
  6. method.invoke(list, str);    //在list上调用add方法,用反射技术

  7. ArrayList<String> list=new ArrayList<String>();
  8. Method method=list.getClass().getMethod("add",Object.class);
  9. Integer i= new Integer(5);               
  10. method.invoke(list, i);    //在list上调用add方法,用反射技术



复制代码

评分

参与人数 1技术分 +1 收起 理由
贺奕凯 + 1

查看全部评分

1 个回复

倒序浏览
本帖最后由 25343215 于 2013-12-3 14:05 编辑

这段代码,System.out.println((Object)list2.get(0));需要强制类型转换。才能运行成功

  1. import java.lang.reflect.Method;
  2. import java.util.ArrayList;

  3. public class Test {

  4.         public static void main(String[] args) throws Exception {

  5.                 // 为何这个不可以
  6.                 // java.lang.Integer cannot be cast to java.lang.String

  7.                 ArrayList<Integer> list = new ArrayList<Integer>();
  8.                 Method method = list.getClass().getMethod("add", Object.class);
  9.                 String str = "添加字符串!"; // 创建字符串
  10.                 method.invoke(list, str); // 在list上调用add方法,用反射技术
  11.                 System.out.println(list.get(0));

  12.                 ArrayList<String> list2 = new ArrayList<String>();
  13.                 Method method2 = list2.getClass().getMethod("add", Object.class);
  14.                 Integer i = new Integer(5);
  15.                 method2.invoke(list2, i); // 在list上调用add方法,用反射技术
  16.                 System.out.println((Object)list2.get(0));
  17.         }
  18. }
复制代码


评分

参与人数 1技术分 +1 收起 理由
贺奕凯 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马