本文共 1018 字,大约阅读时间需要 3 分钟。
整体思路就是:
1:新建一个ArrayList<integer>集合
2:然后使用反射,返回ArrayList的class对象
3:使用class中的getmethod方法,找到ArrayList中的 add方法(此方法是添加元素的时候用的)
3:使用method类中的invoke方法,将字符串添加到集合中
4:遍历集合 输出字符串。
//导包import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.ArrayList;/** * 使用反射在 ArrayList这个集合中添加一个字符串数据; * * @author Starry */public class ArrayListStringDemo { // 主程序入口 public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { // 定义一个ArrayList集合 泛型类型为Integer ArrayList arl = new ArrayList (); arl.add(3); // 将上面定义的Arraylist 返回Arraylist的class对象 Class clazz = arl.getClass(); // 获取Arraylist 类里面的add方法 Method method = clazz.getMethod("add", Object.class); // 对arl对象调用由 Method 对象表示的底层方法 ,向集合中添加字符串 method.invoke(arl, "这是一个字符串"); method.invoke(arl, "这是两个字符串"); // 方法1:使用增强for来循环输出 集合中的数据 for (Object item : arl) { System.out.println(item); } }}
转载地址:http://asxvi.baihongyu.com/