黑马程序员技术交流社区

标题: 反射 [打印本页]

作者: zl78365336    时间: 2013-12-3 13:41
标题: 反射
本帖最后由 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方法,用反射技术



复制代码

作者: 25343215    时间: 2013-12-3 13:55
本帖最后由 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. }
复制代码







欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2