黑马程序员技术交流社区

标题: 分享:泛型为Integer的ArrayList中存放一个String类型的对象 [打印本页]

作者: 乞文超    时间: 2012-4-21 10:13
标题: 分享:泛型为Integer的ArrayList中存放一个String类型的对象
public class insertStrToArray {
         public static void main(String[] args) throws Exception {
                 ArrayList<Integer> list = new ArrayList<Integer>();
                 Method methodAddString = list.getClass().getMethod("add", Object.class);
                 methodAddString.invoke(list, "abc");
                 System.out.println(list);
         }
}这个可以通过反射的方式实现,因为泛型的作用层在编译时。而反射直接获得了add方法的字节码跳过编译层在运行时直接添加。这样就骗过了编译。
作用嘛,比如你得这个集合里存放int类型的数据,但是有及个别的地方需要添加其他类型的数据。就可以用上了!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2