Visual Studio 2005
Gets the public constructor that takes the given arguments.
public java.lang.reflect.Constructor getConstructor(java.lang.Class[ ] parameterTypes)
Parameters
Parameter | Description |
---|---|
parameterTypes | An array of bf6c9478-b86e-41e1-b8c9-48372912df0a objects representing the arguments to the constructor. A 5c106966-ba6e-4e68-8ed8-e4131d1bebff is thrown if there is no constructor with the given parameter types or if the constructor does not have public access. |
A 6350a6f2-aaa4-4243-a87e-bb08980b51a8 object representing the constructor that accepts the given parameter types.
// class_getconstructor.jsl import java.lang.reflect.Constructor; public class Program { public static void main(String[] args) { try { // Get the Class object associated with this class. Program program = new Program(); Class progClass = program.getClass(); // Find the constructor that only takes a String. Class[] ctorArgs1 = new Class[1]; ctorArgs1[0] = String.class; Constructor strCtor = progClass.getConstructor(ctorArgs1); System.out.println("Constructor found: " + strCtor.toString()); // Find the constructor that takes a String and an int. Class[] ctorArgs2 = new Class[2]; ctorArgs2[0] = String.class; ctorArgs2[1] = Integer.class; Constructor strIntCtor = progClass.getConstructor(ctorArgs2); System.out.println("Constructor found: " + strIntCtor.toString()); } catch (NoSuchMethodException ex) { System.out.println("Constructor doesn't exist or is " + "not public: " + ex.toString()); } } public Program() { } public Program(String str) { this.str = str; } private Program(String str, Integer i) { this.str = str; this.i = i; } private String str = "Hello"; private Integer i = new Integer(0); } /* Output: Constructor found: public Program(java.lang.String) Constructor doesn't exist or is not public: java.lang.NoSuchMethodException */
原文出自:http://msdn.microsoft.com/zh-cn/library/aa986011