方法java.lang.Class.getDeclaredConstructor()可用于获取该类的私有构造函数的构造函数对象。此方法的参数是一个Class对象数组,其中包含构造函数的形式参数类型。
演示此的程序如下所示-
package Test; import java.lang.reflect.*; public class Demo { String str; Double d; public Demo(String str, Double d) { this.str = str; this.d = d; } public static void main(String[] args) { try { Demo obj = new Demo("Apple", 55.983); Class c = obj.getClass(); Class[] arguments = new Class[2]; arguments[0] = String.class; arguments[1] = Double.class; Constructor constructor = c.getDeclaredConstructor(arguments); System.out.println("Constructor = " + constructor.toString()); } catch(NoSuchMethodException e) { System.out.println(e.toString()); } catch(SecurityException e) { System.out.println(e.toString()); } } }
Constructor = public Test.Demo(java.lang.String,java.lang.Double)
现在让我们了解上面的程序。
在该main()
方法中创建了Demo类的对象。然后,数组arguments []存储String.Class和Double.Class对象。最后,该方法getDeclaredConstructor()
可用于获取构造函数对象,并显示该对象。演示这的代码片段如下-
Demo obj = new Demo("Apple", 55.983); Class c = obj.getClass(); Class[] arguments = new Class[2]; arguments[0] = String.class; arguments[1] = Double.class; Constructor constructor = c.getDeclaredConstructor(arguments); System.out.println("Constructor = " + constructor.toString());