黑马程序员技术交流社区

标题: 第二题---主要测试反射 [打印本页]

作者: doglovely    时间: 2016-3-13 14:27
标题: 第二题---主要测试反射
/* 2、ArrayList<Integer> list = new ArrayList<Integer>();
在这个泛型为Integer的ArrayList中存放一个String类型的对象*/

public class Test2 {

        /**
         * @param args
         * @throws InvocationTargetException
         * @throws IllegalAccessException
         * @throws IllegalArgumentException
         */
        public static void main(String[] args) throws Exception {

                // 创建一个ArrayList集合
                ArrayList<Integer> list = new ArrayList<Integer>();
                //集合ArrayList的class对象
                Class c = list.getClass();

                // 用反射机制取得list的add方法方法
                Method method = c.getMethod("add",Object.class);
               
               
                // 调用list集合的add方法,把字符串加到list集合对象中
                method.invoke(list, "hello");
                method.invoke(list, "word");
                System.out.println(list);

        }

}







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