Java.lang.Class.getDeclaredConstructor() 方法
描述
java.lang.Class.getDeclaredConstructor() 方法返回一个Constructor对象,它反映了这个Class对象所代表的类或接口的指定构造函数。 parameterTypes 参数是一个 Class 对象数组,它们按照声明的顺序标识构造函数的形式参数类型。
声明
以下是 java.lang.Class.getDeclaredConstructor() 方法的声明。
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
参数
parameterTypes − 这是参数数组。
返回值
此方法返回具有指定参数列表的构造函数的 Constructor 对象。
异常
NoSuchMethodException − 如果没有找到匹配的方法。
SecurityException − 如果存在安全管理员 s。
示例
下面的例子展示了 java.lang.Class.getDeclaredConstructor() 方法的使用。
package com.tutorialspoint;
import java.lang.reflect.*;
public class ClassDemo {
public static void main(String[] args) {
try {
ClassDemo cls = new ClassDemo();
Class c = cls.getClass();
// constructor with arguments as Double and Long
Class[] cArg = new Class[2];
cArg[0] = Double.class;
cArg[1] = Long.class;
Constructor ct = c.getDeclaredConstructor(cArg);
System.out.println("Constructor = " + ct.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
} catch(SecurityException e) {
System.out.println(e.toString());
}
}
private ClassDemo() {
System.out.println("no argument constructor");
}
public ClassDemo(Double d, Long l) {
this.d = d;
this.l = l;
}
Double d = new Double(3.9d);
Long l = new Long(7687);
}
让我们编译并运行上面的程序,这将产生下面的结果 −
no argument constructor Constructor = public ClassDemo(java.lang.Double,java.lang.Long)

