zoukankan      html  css  js  c++  java
  • java 27

    之前学过的集合里面都有泛型,规定了泛型的类型以后,就不能往这个集合添加除了这个类型之外的类型数据了。

    那么,有什么方法可以越过这个泛型,添加特定类型以外的类型数据么?

      例子:

         往ArrayList<Integer>集合中添加一个字符串String类型的数据

      分析:  

        通过查看ArrayList的add()方法,可以知道,add(E e)。E这个泛型是Object的。

        就可以通过反射来直接调用ArrayList集合的add方法进行添加

     1 public static void main(String[] args) throws Exception {
     2 
     3         // 创建ArrayList集合对象
     4         ArrayList<Integer> array = new ArrayList<Integer>();
     5 
     6         // 直接添加肯定不行
     7         // array.add("hello");
     8 
     9         // 通过查看ArrayList的add()方法,可以知道,add(E e)。E这个泛型是Object的。
    10         // 就可以通过反射来直接调用ArrayList集合的add方法进行添加
    11 
    12         // 获取ArrayList集合的class字节文件对象
    13         Class c = array.getClass();
    14         // 获取add方法,方法需要的参数是Object类的
    15         Method m = c.getMethod("add", Object.class);
    16         // 调用add方法  使用array(AllayList)的add方法,添加“xxx”
    17         m.invoke(array, "hello");
    18         m.invoke(array, "world");
    19         
    20         System.out.println(array); //[hello, world]
    21         
    22     }
  • 相关阅读:
    管道流
    构造方法中用泛型
    代码实现长提闪烁
    关联事件,向窗体中添加控件,设置控件属性等系列操作
    picturebox中添加图片
    typeof gettype
    groupbox
    static用法
    运算符重载
    类修饰符
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5967139.html
Copyright © 2011-2022 走看看