1. 程式人生 > >JAVA中利用反射,往集合中插入其他型別的資料

JAVA中利用反射,往集合中插入其他型別的資料

 

 @Test
    public void TestReflectList() {

        List<String> list=new ArrayList<>();
        list.add("A");
        list.add("B");

        //獲取類物件
        Class<?> l=list.getClass();


        try {
            //獲取類物件中的方法             類中方法名   方法的引數型別
            Method  m=l.getDeclaredMethod("add",Object.class);
            //執行此方法  list為物件,100為傳入的引數
            m.invoke(list,100);

            System.out.println(list);


        } catch (Exception e) {
            e.printStackTrace();
        }


    }