Java-反射之擷取方法資訊

來源:互聯網
上載者:User

標籤:反射機制   ref   簡單   訪問   類型   表示   函數   --   code   

簡單地學習了一下Java的反射機制和Class類,我們就可以通過這種方式來擷取一個類的詳細資料。

1.獲得基礎資料型別 (Elementary Data Type)和簡單的類的類類型

1     public static void main(String[] args) {2         Class c1 = int.class; // 拿到int的類類型 -- 相當於是int位元組碼3         Class c2 = Integer.class; //Integer的類類型--與上面的int是不一樣的4         Class c3 = Void.class;5         System.out.println(c1.getName());6         System.out.println(c2.getName()); //取得類的完整名稱7         System.out.println(c2.getSimpleName()); //取得簡單的類名8 9     }

2.列印類的資訊--成員函數

/**     * 列印類的資訊,包括類的成員函數、成員變數     *      * @param obj     */    public static void printClassMessage(Object obj) {        Class c1 = obj.getClass(); // 擷取該類的類類型,如果該類是Object的話,表示是Object的類類型,否則是Obejct子類的類類型        System.out.println(c1.getName()); //獲得該類的類名        /**         * 萬事萬物結尾對象,所以在類中,一個方法也是對象,是Method的對象         * getMethods擷取的是所有的public方法,包括從父類繼承過來的方法         * getDeclaredMethods 擷取的是自己聲明的方法,不論是什麼存取權限         */        Method []method = c1.getMethods();        for(int i = 0, n = method.length; i< n; i++)        {            //得到的是方法傳回值類型的類類型--比如String,則得到的是String.class            Class type = method[i].getReturnType();            System.out.print(type.getSimpleName()+" ");            //列印方法的名字            System.out.print(method[i].getName() + "(");            //擷取參數列表的類類型            Class [] methodParameterTypes = method[i].getParameterTypes();            for(int j = 0, m = methodParameterTypes.length; j < m; j++)            {                System.out.print(methodParameterTypes[j].getSimpleName() + " ");            }            System.out.println(")");        }    }

 

3.擷取構造方法的資訊

 1         /** 2          * 構造方法也是對象, 是Java.lang.reflect.Constructor的對象 3          * getConstructors獲得所有的public構造方法 4          * getDeclaredConstructors獲得所有的構造方法 5          */ 6         Constructor[] declaredConstructors = c1.getDeclaredConstructors(); 7         for(int i = 0, n = declaredConstructors.length; i < n; i++) 8         { 9             System.out.print(declaredConstructors[i].getName() + "(");10             Class ParameterTypes[] = declaredConstructors[i].getParameterTypes();11             for(int j = 0, m =  ParameterTypes.length; j < m; j++)12             {13                 System.out.print(ParameterTypes[j].getName() + " ");14             }15             System.out.println(")");16         }

 

Java-反射之擷取方法資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.