在泛型为Integer的ArrayList中存放一个String类型的对象

来源:互联网 发布:ubuntu中安装qq国际版 编辑:程序博客网 时间:2024/05/16 17:23

通过反射获取list集合的所有方法,然后把字符串存入集合中。

import java.lang.reflect.InvocationTargetException;public class reflectDemo {    public static void main(String[] args) throws NoSuchMethodException,            NoSuchMethodException, InvocationTargetException,            InvocationTargetException, IllegalAccessException {        ArrayList<Integer> list = new ArrayList<Integer>();        for (int i = 0; i < 6; i++) {            list.add(i);        }        String str = "我是字符串";        Method method = list.getClass().getMethod("add", Object.class);        method.invoke(list, str);        Iterator<Integer> iterator = list.iterator();        while (iterator.hasNext()) {            System.out.print(iterator.next()+" ");        }    }}

输出结果:

0 1 2 3 4 5 我是字符串 
阅读全文
0 0
原创粉丝点击