非深入探尋Java反射機制 (Constructor)

來源:互聯網
上載者:User

使用Java Reflection機制,我們可以在運行時探尋一個類的建構函式並且產生該類的執行個體。這些是通過
java.lang.reflect.Constructor 實現的。

Obtaining Constructor Objects

如下方法可以獲得一個類的所有public建構函式

Class myClass = Class.forName("A");Constructor[] constructors = myClass.getConstructors();

如果知道了建構函式的參數類型,那麼就可以直接查詢該public  constructor

A.class檔案

package tao.xiao.action;public class A implements IT1 {public A(String s) {}public A(double x, String y, int[] z) {}public A(int a) {}}

HelloJava.class檔案的main部分

Class myClass = Class.forName("tao.xiao.action.A");Constructor constructor = myClass.getConstructor(new Class[] {String.class});System.out.println(constructor);constructor = myClass.getConstructor(new Class[] {double.class, String.class, int[].class});System.out.println(constructor);constructor = myClass.getConstructor(new Class[] {int.class});System.out.println(constructor);

結果為

public tao.xiao.action.A(java.lang.String)public tao.xiao.action.A(double,java.lang.String,int[])public tao.xiao.action.A(int)

下一章:非深入探尋Java反射機制(Fields)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.