Source code:
1 package reflex; 2 3 Import Java. util. list; 4 5/** use reflection to instantiate objects */6 public class person {7 public person () {8 system. out. println ("Call the no-argument constructor"); 9} 10 11 Public Person (string name) {12 system. out. println (name); 13} 14 15 public person (string name, int age) {16 system. out. println (name + ":" + age); 17} 18/** private constructor, which cannot be called externally, but can be called through reflection */19 private person (list List) {20 system. out. println ("calling a private parameter-free constructor"); 21} 22}
1 package reflex; 2 3 Import Java. lang. reflect. constructor; 4 Import Java. util. arraylist; 5 import Java. util. list; 6 7 Import Org. JUnit. test; 8/** 9*1. getconstructor returns the public constructor 10*2 conforming to the parameter. getdeclaredconstructor returns the constructor 11*3 that meets the parameters. setaccessible brute force reflection: You can use a private constructor to create an object instance 12 */13 public class testreflex {14 @ test15 public void test1 () throws exception {16 class clazz = Class. forname ("reflex. person "); 17 constructor = clazz. getconstructor (null); 18 person = (person) constructor. newinstance (null); 19} 20 @ test21 public void Test2 () throws exception {22 class clazz = Class. forname ("reflex. person "); 23 constructor = clazz. getconstructor (string. class); 24 person = (person) constructor. newinstance ("Xiaoxiao"); 25} 26 @ test27 public void test3 () throws exception {28 class clazz = Class. forname ("reflex. person "); 29 constructor = clazz. getconstructor (string. class, Int. class); 30 person = (person) constructor. newinstance ("Xiaoxiao", 21); 31} 32 @ test33 public void test4 () throws exception {34 class clazz = Class. forname ("reflex. person "); 35 constructor = clazz. getdeclaredconstructor (list. class); 36 constructor. setaccessible (true); // brute force reflection. You can use a private constructor to create an object instance 37 person = (person) constructor. newinstance (New arraylist (); 38} 39}
Reflection (1)-reflection Class Construction Method