java.lang.Class.getDeclaredConstructor()%uA0方法返回一个Constructor对象,它反映此Class对象所表示的类或接口指定的构造函数。parameterTypesparameter是确定构造函数的形参类型,在Class对象声明顺序的数组。
声明
以下是java.lang.Class.getDeclaredConstructor()方法的声明
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException
参数
-
parameterTypes%uA0-- 这是参数数组。
返回值
此方法返回具有指定参数列表构造函数的构造函数对象。
异常
-
NoSuchMethodException%uA0-- 如果没有找到匹配的方法。
-
SecurityException%uA0--如果安全管理存在。
例子
下面的例子显示java.lang.Class.getDeclaredConstructor()方法的使用。
package com.yiibai 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)