反射可以越过泛型的检查(基础)

ArrayList的泛型我设置为Integer
通过反射,我将String类型的数据插入到ArrayList数组当中

public class main {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ArrayList<Integer> arrayList = new ArrayList<Integer>();

        Class<? extends ArrayList> aClass = arrayList.getClass();
        //Method    [Class].getMethod(String name, Class<?>... parameterTypes)
        //返回一个Method对象,该对象反映此Class对象表示的类或接口的指定公共成员方法,没有参数可以省略“, Class<?>... parameterTypes”
        Method add = aClass.getMethod("add", Object.class);
        //Object    [Method].invoke(Object obj, Object... args)
        //在Method 具有指定参数的指定对象上调用此对象表示的基础方法,invoke参数类型对应getMehod方法的参数类型
        add.invoke(arrayList,"一二三");
        add.invoke(arrayList,"one");

        System.out.println(arrayList);
    }
}

输出台输出:

[一二三, one]

posted @ 2021-03-02 23:18  丰北丰  阅读(60)  评论(0)    收藏  举报