1 Privateuser copyfieldvalues (user userData, user user) {2field[] Fields =User.getclass (). Getdeclaredfields ();3string[] FieldNames =getfieldnames (fields);4 for(inti = 0; i < fieldnames.length; i++) {5Object value =Getfieldvaluebyname (fieldnames[i], user);6 if(Value! =NULL) {7 Setfieldvaluebyname (Fieldnames[i], UserData, Value,fields[i].gettype ());8 }9 }Ten returnUserData; One}
1 Private string[] Getfieldnames (field[] fields) {2 New String[fields.length]; 3 for (int i = 0; i < fields.length; i++) {4 fieldnames[i] = fields[i].getname () ; 5 }6 return fieldnames; 7 }
1 PrivateObject Getfieldvaluebyname (String fieldName, object o) {2Object value =NULL;3 Try {4String getter = "Get" +initstr (fieldName);5Method method =O.getclass (). GetMethod (getter);6Value =Method.invoke (o);7}Catch(Exception e) {8 e.printstacktrace ();9 }Ten returnvalue; One}
1 Private voidSetfieldvaluebyname (String fieldName, Object o, Object value, class<?>type) {2 Try {3String setter = "Set" +initstr (fieldName);4Method method =O.getclass (). GetMethod (setter, type);5 Method.invoke (o, value);6}Catch(Exception e) {7 e.printstacktrace ();8 }9}
1 Private string Initstr (String fieldName) {2 return fieldname.substring (0, 1). toUpperCase () + fieldname.substring (1); 3 }
Java reflection implements a copy of a class through getter and setter methods