黑马程序员技术交流社区

标题: 反射可以这样用... [打印本页]

作者: sofeel    时间: 2015-2-25 23:36
标题: 反射可以这样用...
3、 ArrayList<Integer> list = new ArrayList<Integer>();
在这个泛型为Integer的ArrayList中存放一个String类型的对象。
提示:用反射实现。


作者: 时间都去哪了    时间: 2015-2-26 22:05
package com.kvku.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

public class ArrayListTest {
        public static void main(String[] args) throws NoSuchMethodException,
                        SecurityException, IllegalAccessException,
                        IllegalArgumentException, InvocationTargetException {
                ArrayList<Integer> list = new ArrayList<Integer>();
                Class c = list.getClass();
                Method method = c.getMethod("add", Object.class);
                method.invoke(list, "hello");
                method.invoke(list, "world");
                System.out.println(list);
        }
}

作者: ㏒假™面具    时间: 2015-2-27 03:06
  1. package test_1;

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

  4. /**
  5. * @author 面具
  6. *
  7. */
  8. public class ArrayListDemo {

  9.         /**
  10.          * @param args
  11.          * @throws Exception
  12.          * @throws NoSuchMethodException
  13.          */
  14.         public static void main(String[] args) throws NoSuchMethodException, Exception {
  15.                 ArrayList<Integer> list = new ArrayList<Integer>();
  16. //                获取ArrayList类的字节码文件对象
  17.                 Class clazz = list.getClass();
  18. //                获取方法的Method实例
  19.                 Method m = clazz.getMethod("add", Object.class);
  20. //                添加元素
  21.                 m.invoke(list, "高圆圆");
  22.                 System.out.println(list);
  23.         }

  24. }
复制代码

作者: 竹叶君子    时间: 2015-2-27 09:18
赞一个,顶起!
作者: sofeel    时间: 2015-2-27 10:27
㏒假™面具 发表于 2015-2-27 03:06

额...
高圆圆也被你装进集合了{:2_34:}
作者: ㏒假™面具    时间: 2015-2-27 23:19
sofeel 发表于 2015-2-27 10:27
额...
高圆圆也被你装进集合了

我女神,必须藏起来。。哈
作者: a410709560    时间: 2015-2-28 00:03
谢谢分享!!!
作者: mengxiang1993    时间: 2015-2-28 08:48
顶一个,但是原理是什么呢?怎么就骗过编译器呢?
作者: sofeel    时间: 2015-2-28 23:06
mengxiang1993 发表于 2015-2-28 08:48
顶一个,但是原理是什么呢?怎么就骗过编译器呢?

反射就是这么粗暴,它破环了封装性和安全性,一路高歌。
但这哥们就是耗资源。




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