Java Constructor and Java Constructor
Insert the code segment and recall it next time.
Create a Person class first. The Code is as follows:
Public class Person {private String name; private int age; public Person () {} public Person (String name, int age) {this. name = name; this. age = age;} Person (String name) {this. name = name;} private Person (int age) {this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String toString () {return "name" + this. getName () + ", age" + this. getAge ();}}
It contains various constructor methods and methods. The following ConstructorDemon class is constructed (note that the two classes must be in the same package) for Demonstration:
Public class ConstructorDemon {public static void main (String [] args) {try {Class <?> C = Class. forName ("Person"); // obtain all public constructor System. out. println ("all methods for constructing a shared-Health ELE. Me"); Constructor [] constructor = c. getConstructors (); for (int I = 0; I <constructor. length; I ++) {System. out. println (constructor [I]. toGenericString ();} // obtain the public Parameter Method of the specified parameter type: System. out. println ("Get the public Constructor of the specified type"); try {Constructor constru = c. getConstructor (new Class [] {String. class, int. class}); System. out. println (constru. toGenericSt Ring ();} catch (Exception e) {// TODO Auto-generated catch block System. out. println ("the specified type of constructor does not exist! ");} // Obtain the public method of the specified parameter type, without limiting the access level System. out. println ("obtain the public Constructor of the specified type without limit on the access level"); try {Constructor constru = c. getDeclaredConstructor (new Class [] {int. class}); System. out. println (constru. toGenericString (); // here a private constructor is obtained} catch (Exception e) {e. printStackTrace ();} // obtain all the constructor Methods: System. out. println ("Get all constructor methods"); constructor = c. getDeclaredConstructors (); for (int I = 0; I <constructor. length; I ++) {System. out. println (constructor [I]. toGenericString ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace ();}}}
After clicking run, the running result is as follows:
All methods for constructing a shared-health system
Public Person (java. lang. String, int)
Public Person ()
Obtains the public constructor of the specified type.
Public Person (java. lang. String, int)
Obtains a public constructor of the specified type, without limiting the access level.
Private Person (int)
Obtain all constructor Methods
Private Person (int)
Person (java. lang. String)
Public Person (java. lang. String, int)
Public Person ()