반사를 통해 집합 범형의 본질을 이해하다

3880 단어
Class, Method를 통해 범형의 본질을 알 수 있습니다. 바로 제가 쓴 코드로 하겠습니다. 주석이 상세합니다.
package com.imooc.classdemo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;



public class MethodDemo1 {
    public static void main(String[] args){

        ArrayList list = new ArrayList();

        ArrayList list1 = new ArrayList();
        list1.add("hello");
        //list1.add(20);      
        Class c1=list.getClass();
        Class c2=list1.getClass();
        System.out.println(c1==c2);
        //              

        /*
         * /c1==c2    true                  
         * java      ,        ,        ,        
         *   :              ,    
         */

        try {
//          Method m1 = c1.getMethod("add", Object.class);
            Method m2 = c2.getMethod("add", Object.class);
            m2.invoke(list1, 20);//            
            System.out.println(list1.size());
            System.out.println(list1);
            /*
             * for(String string:list1){
             *  System.out.println(string);
            }
                       ,    
             */

        } catch (NoSuchMethodException | SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

좋은 웹페이지 즐겨찾기