PackageReflet;Importjava.util.List; Public classPerson { PublicString name= "Hahaah"; PublicPerson ()//no parameter constructor{System.out.println ("Person"); } PublicPerson (String name)//Parametric Constructors{System.out.println (name); } PublicPerson (String name,intPassword//Parametric Constructors{System.out.println (name+":"+password); } PrivatePerson (List List)//Parametric Constructors{System.out.println ("Person List"); }
PackageReflet;ImportJava.lang.reflect.Constructor;Importjava.util.ArrayList;Importjava.util.List;Importorg.junit.Test;//the constructor of the reflection class that creates the object of the class Public classDemo {//Reflection Constructor: Public person@Test Public voidTest1 ()throwsException {Class clazz=class.forname ("Reflet.person");//Load ClassConstructor C=clazz.getconstructor (NULL); Person P= (person) c.newinstance (NULL); System.out.println (P.name); } //Reflection constructor: Public person (String name)@Test Public voidTest2 ()throwsException {Class clazz=class.forname ("Reflet.person"); Constructor C=clazz.getconstructor (String.class); Person P= (person) c.newinstance ("SDQAWJUHUGBYUGDR"); System.out.println (P.name); } //Reflection constructor: Public person (String name,int password)@Test Public voidTest3 ()throwsException {Class clazz=class.forname ("Reflet.person"); Constructor C=clazz.getconstructor (String.class,int.class); Person P= (person) c.newinstance ("Sdqawjuhugbyugdr", 45); System.out.println (P.name); } //Reflection constructor: Private person (list list)@Test Public voidTest4 ()throwsException {Class clazz=class.forname ("Reflet.person"); Constructor C=clazz.getdeclaredconstructor (List.class);//because this function is a private type, use GetdeclaredconstructorC.setaccessible (true);//violent reflexes (the function is to allow private access to the outside world)Person p= (person) c.newinstance (NewArrayList ()); System.out.println (P.name); } //another way to create an object: The following test5 is equivalent to Test1@Test Public voidTEST5 ()throwsException {Class clazz=class.forname ("Reflet.person"); Person P=(person) clazz.newinstance (); System.out.println (P.name); } }
Inverse of this type of construction method (the reflection class is used when writing frames)