Loading

通过反射越过泛型检查

因为泛型只在编译期有效,在运行期会被擦除掉,所以可以通过反射越过泛型检查,例如在泛型为Integer的集合中添加String对象:

public class Demo2_reflect {

    public static void main(String[] args) throws Exception {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(10);

        Class clazz = Class.forName("java.util.ArrayList");
        Method m = clazz.getMethod("add", Object.class);
        m.invoke(list, "abc");
        System.out.println(list);

    }

}

这样就在list集合中添加了String

posted @ 2017-03-03 11:14  leon_x  阅读(27)  评论(0)    收藏  举报