- package com.itheima;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
- import java.util.ArrayList;
- import java.util.List;
- public class Test25 {
- public static void main(String[] args) {
- List<Integer> list = new ArrayList<Integer>();
- String str = "我是一个字符串";
- Integer i = 10;
- Class clazz = list.getClass(); //得到class
- Method m = null;
- try {
- m = clazz.getMethod("add", Object.class); //得到add方法对象
- } catch (NoSuchMethodException | SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //正常添加
- list.add(i);
- try {
- //反射添加
- m.invoke(list, i);
- m.invoke(list, str);
- } catch (IllegalAccessException | IllegalArgumentException
- | InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- //遍历
- for (Object obj : list) {
- System.out.println(obj);
- }
- }
- }
复制代码
|