Just learned the reflection, feel the function of reflection is very strong, so want to write a blog record of their own learning results.
Use reflection to create objects.
Class c1=class.forname ("Test. Person ");//create a class from the class name, where Test.person is just a class name. This person class code is//At the bottom of this article/*** Scenario 1: Call the parameterless constructor to create the object*/Person P=c1.newinstance ();//this creates it./*** Scenario 2: Calling a method with a parameter constructor*/Constructor CS=c1.getconstructor (String.class,int.class);//what is written in parentheses is the class of the parameter types of the constructor method, which is the addition of the following. class.Person p= (person) cs.newinstance ("Zhang San", 22);//invoking a constructor method to build an object
View Code
Use reflection to set private properties
Try { Class clazz=class.forname ("Testperson"); Person P=(person) clazz.newinstance (); Field F1=clazz.getdeclaredfield ("name"); F1.setaccessible (true); // set whether private properties can be manipulated F1.set (P, "WFADF"); System.out.println (F1.get (P)); Catch (Exception e) { // TODO auto-generated catch block throw New runtimeexception (e); }
Person Class Code
Packagetest; Public classPerson {PrivateString name; Private intAge ; PublicPerson () {} PublicPerson (String name,intAge ) { This. Name =name; This. Age =Age ; } PublicString GetName () {returnname; }/*Public void SetName (String name) {this.name = name; }*/ Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; }}
Reflection in Java, knowing the class name creates a class, and you can set the value of a private property