Java reflection implements a copy of a class through getter and setter methods

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.