Java reflection, know the class name to create a class, you can also set the value of the private property, java private
I just learned reflection, and I feel that reflection is powerful. So I want to write a blog to record my learning achievements.
Use reflection to create objects.
Class c1 = Class. forName ("test. Person"); // create a Class by Class name. Here test. person is just a Class name ,. The person class code is at the bottom of // This article/*** Case 1: Call the construction method without parameters to create an object */Person p = c1.newInstance (); // In this case, the/*** scenario 2 is created: Call the construction method with parameters */Constructor cs = c1.getConstructor (String. class, int. class); // The parameter type of the constructor is written in the brackets, that is, it is added later. class is ready for Person p = (Person) cs. newInstance ("Zhang San", 22); // call the constructor to generate an objectView Code
Use reflection to set Private attributes
Try {Class clazz = Class. forName ("testPerson"); Person p = (Person) clazz. newInstance (); Field f1 = clazz. getDeclaredField ("name"); f1.setAccessible (true); // sets whether private attributes f1.set (p, "wfadf") can be operated; System. out. println (f1.get (p);} catch (Exception e) {// TODO Auto-generated catch block throw new RuntimeException (e );}
Person code
package test;public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; 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; }}