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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sofeel 中级黑马   /  2015-2-25 23:36  /  1144 人查看  /  9 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

3、 ArrayList<Integer> list = new ArrayList<Integer>();
在这个泛型为Integer的ArrayList中存放一个String类型的对象。
提示:用反射实现。

9 个回复

倒序浏览
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);
        }
}

评分

参与人数 1黑马币 +1 收起 理由
sofeel + 1 赞一个!

查看全部评分

回复 使用道具 举报 1 0
  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 03:07

评分

参与人数 1技术分 +1 收起 理由
lwj123 + 1

查看全部评分

回复 使用道具 举报
赞一个,顶起!
回复 使用道具 举报

额...
高圆圆也被你装进集合了{:2_34:}
回复 使用道具 举报
sofeel 发表于 2015-2-27 10:27
额...
高圆圆也被你装进集合了

我女神,必须藏起来。。哈
回复 使用道具 举报
谢谢分享!!!
回复 使用道具 举报
顶一个,但是原理是什么呢?怎么就骗过编译器呢?
回复 使用道具 举报
sofeel 中级黑马 2015-2-28 23:06:50
9#
mengxiang1993 发表于 2015-2-28 08:48
顶一个,但是原理是什么呢?怎么就骗过编译器呢?

反射就是这么粗暴,它破环了封装性和安全性,一路高歌。
但这哥们就是耗资源。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马