first, the preparation of knowledge:
Java Reflection mechanism
JavaBean of handling transactions
Common methods for manipulating string
second, the simulation steps
Here we simulate the automatic assignment in struts by dynamically acquiring the value of the property from the reflection mechanism.
1, first create a simple user class containing two attributes username and userid, and Getter, setter method:
Class User {
Publicuser () {}
Privatestring username;
privatestring userid;
Publicstring GetUserid () {
return userid;
}
Public Voidsetuserid (String userid) {
This.userid = userid;
}
Publicstring GetUserName () {
return username;
}
Public Voidsetusername (String username) {
This.username = Username;
}
}
2. Next create the object User1 of the user class, and then dynamically assign all properties of the User1 object to the newly created user2 through the reflection mechanism:
Create a User1 object
User User1 = new user ();
User1.setusername ("arthinking");
User1.setuserid ("001");
String username = "arthinking";
String userid = "001";
Get class by User1 object
Class<?> ClassType =user1.getclass ();
Generating User2 objects
Object user2 = Classtype.getconstructor (newclass[]{}). newinstance (New object[]{});
Get all the properties from the User1 corresponding class object
field[] fields = Classtype.getdeclaredfields ();
for (int i=0; i<fields.length; i++) {
Field field= Fields[i];
Dynamically generating getter and setter methods
Stringfieldname = Field.getname ();
Stringfirstchar = fieldname.substring (0,1). toUpperCase ();
Stringgettername = "Get" + Firstchar + fieldname.substring (1);
Stringsettername = "Set" + Firstchar + fieldname.substring (1);
Methodgetter = Classtype.getmethod (gettername);
Methodsetter = Classtype.getmethod (Settername, Newclass[]{field.gettype ()});
Execute getter method to get the value of the current domain
Objectresult = Getter.invoke (user1);
Perform setter to assign value to User2
Setter.invoke (User2, New Object[]{result});
}
Reflection Learning 2-dynamically obtaining the value of a property through a reflection mechanism simulates the automatic assignment of struts