JAVA 反射练习

package Reflects;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/*
    练习1:我有一个ArrayList<Integer>集合,现在我想在这个集合中添加一个字符串数据如何实现呢?
 */
public class ReflectDemo{
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        ArrayList<Integer> array = new ArrayList<Integer>();
        Class<? extends ArrayList> c = array.getClass();
        Method m = c.getMethod("add", Object.class);
        m.invoke(array,"hello");
        m.invoke(array,"world");
        m.invoke(array,"java");

        System.out.println(array);
    }
}

 

posted @ 2022-04-28 20:35  phpwyl  阅读(46)  评论(0编辑  收藏  举报