1. 程式人生 > >獲取構造器的信息

獲取構造器的信息

types getname spa public lis 沒有 out 獲取 exception

獲取類構造器的用法與上述獲取方法的用法類似,如:


import java.lang.reflect.*;

public class constructor1 {

    public constructor1() {

    }


    protected constructor1(int i, double d) {

    }


    public static void main(String args[]) {

        try {

            Class cls = Class.forName("constructor1");

            Constructor ctorlist[] = cls.getDeclaredConstructors();

            for (int i = 0; i < ctorlist.length; i++) {

            Constructor ct = ctorlist[i];

            System.out.println("name = " + ct.getName());

            System.out.println("decl class = " + ct.getDeclaringClass());

            Class pvec[] = ct.getParameterTypes();

            for (int j = 0; j < pvec.length; j++)

            System.out.println("param #" + j + " " + pvec[j]);

            Class evec[] = ct.getExceptionTypes();

            for (int j = 0; j < evec.length; j++)

            System.out.println("exc #" + j + " " + evec[j]);

            System.out.println("-----");

            }

        } catch (Throwable e) {

            System.err.println(e);

        }

    }

}

這個例子中沒能獲得返回類型的相關信息,那是因為構造器沒有返回類型。

這個程序運行的結果是:


name = constructor1

decl class = class constructor1

-----

name = constructor1

decl class = class constructor1

param #0 int

param #1 double

獲取構造器的信息