java类反射越过泛型检查


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

//通过反射越过泛型检查
public class ReflectDemo6 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(10);
        integers.add(20);
        integers.add(30);
//        不能通过检查
//        integers.add("hello");

        //通过反射越过检查
        Class<? extends ArrayList> integersClass = integers.getClass();
        Method add = integersClass.getMethod("add", Object.class);
        add.invoke(integers,"hello");

        System.out.println(integers);
    }
}


posted @ 2021-05-03 22:08  code-G  阅读(47)  评论(0编辑  收藏  举报