绕过泛型,通过反射把 String 添加到 List 中

绕过泛型,通过反射把 String 添加到 List<Integer> 中

public class ArrayListDemo {

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

        // list.add(1);
        // list.add(2);
        // list.add("hello");

        Class c = list.getClass();
        Method method = c.getMethod("add",Object.class);
        method.invoke(list,"hello");
        method.invoke(list,"world");
        method.invoke(list,"liwei");

        System.out.println(list);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41040268/article/details/81296199
今日推荐