Copy the properties of two objects using Java

Source: Internet
Author: User

The recent interaction with Java reflects a bit more, probably because the future direction of the architect's sake, they mainly engaged in business. I can do the architecture and draw some flowchart all day.

Although for only one year internship experience of me, do not know whether this is good, but I still that sentence, regardless of bad, first walk, after all, can learn a lot of things, but also can exercise their thinking ability.

The ability to express, because their products do a good job, you are not to express, say no advantages, then you will be defeated.

Create an entity class first user

Package com.mine.practice.copyproperty.entity;/**  *  * @author 2014-11-6 a.m. 10:28:10   * @version V1.0   * /public class User {private int id;private string Name;private string pwd;private double Idg;public double getidg () {retur n IdG;} public void Setidg (double idg) {this.idg = IdG;} Public String getpwd () {return pwd;} public void SetPwd (String pwd) {this.pwd = pwd;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}


Then there is the exact copy of the code that has been tested.

Package Com.mine.practice.copyproperty.test;import Java.lang.reflect.field;import com.mine.practice.copyproperty.entity.user;/** * Attribute copy * @author 2014-11-6 a.m. 10:29:32 */public class Testcopyproperty {/ * * Business Requirements: * For some businesses to update data for some or some class, you only want to update some fields of the class, and the other fields use the previous values. * * Problems encountered: * When some businesses need to increase or decrease the number of fields in a class, modify the field name, the foreground may only need to modify one place to solve.    * But in the background due to the way the event is handled, so there will be many places to use, it is difficult to modify.   * * Main Solution: * Even if the number of fields or the field name modified after the background code does not need to be modified. * * Solution: * Revised on the basis of previous solutions.      * By iterating through all the properties of the class, and then getting the property values of the new class, if the new class's property value is not null, the empty string, the default value of the base type, the property value of the new object is assigned to the old object property * * Advantages: 1, even if you add or modify the number of fields in the background does not 2, even if you modify the field name or type background does not need to change * * Disadvantage: 1, will traverse all the properties of a class, and determine the new object's property value: whether it exists and whether it is a default value. The performance of the bulk data is somewhat poor * 2, because the basic data type will have default values, so the framework does not know whether the value of this field should not be modified to the new object.  * * * @author 2014-11-6 a.m. 11:01:03 * @param args * @throws SecurityException * @throws nosuchfieldexception * @throws illegalargumentexception * @throws illegalaccessexception * @modificationHistory ========================= Logical OR functional significant change record * @modify bY User: {modified person} 2014-11-6 * @modify by reason:{reason} */public static void Main (string[] args) throws SecurityException, Nosuc Hfieldexception, IllegalArgumentException, illegalaccessexception {///old object User Olduser = new User (); Olduser.setid (1); O Lduser.setname ("name1"); Olduser.setpwd ("pwd1"); Olduser.setidg (1.2); System.out.println ("Old object in the database");p rint (olduser);//New object User newuser = "user" (); Newuser.setname ("name2"); System.out.println ("new objects passed by the foreground");p rint (NewUser);//function requirements//change the ID and name of the previous old object, but PWD does not need to modify Copyproperty (Olduser, NewUser); System.out.println ("----------old object Modified-------------");p rint (olduser);} /** * * @author 2014-11-6 a.m. 11:26:36 * @param olduser * @param newuser * @throws nosuchfieldexception * @throws SECU Rityexception * @throws illegalaccessexception * @throws illegalargumentexception * @modificationHistory ============== =========== logical OR functional change record * @modify by User: {modifier} 2014-11-6 * @modify by reason:{cause} */@SuppressWarnings ("Rawtypes") priv ate static void Copyproperty (User olduser,uSer newuser) throws SecurityException, Nosuchfieldexception, IllegalArgumentException, illegalaccessexception{// The new Classclass Newclass = Newuser.getclass ();//old Classclass Oldclass = Olduser.getclass ();//All properties of the class field[] Newfields = Newclass.getdeclaredfields ();//new attribute field Newfield = null;//old attribute field Oldfield = null;for (field f:newfields) {// The property name in the class is string fieldName = F.getname ();//Gets the property by property name Newfield = Newclass.getdeclaredfield (fieldName);//Gets the value of the property to be set to True indicates that the reflected object should cancel the Java language access check when it is used. A value of false indicates that the reflected object should implement a Java language access check. Newfield.setaccessible (TRUE);//Gets the value on the object based on the attribute object newObject = Newfield.get (NewUser);//filter empty properties or some default if (Iscontinue ( NewObject)) {continue;} Oldfield = Oldclass.getdeclaredfield (fieldName); oldfield.setaccessible (true); Oldfield.set (Olduser, NewObject);}} /** * Whether to jump out of this cycle * @author 2014-11-6 a.m. 11:37:22 * @param Object * @return true is null or default * False no default value */PR Ivate Static Boolean Iscontinue (Object object) {if (object = = NULL | | "". Equals (object)) {return true;} String valuestr = object.tostring (); if ("0". Equals (VALUESTR) | | "0.0". Equals (Valuestr)) {return true;} return false;} /** * * @author 2014-11-6 a.m. 10:57:32 * @param user */private static void print (user user) {System.out.println ("ID:" + User.getid ()); System.out.println ("Name:" +user.getname ()); System.out.println ("pwd:" +user.getpwd ()); System.out.println ("IdG:" +USER.GETIDG ());}}

function is simple, but learn some new knowledge or very open Sen.

Copy the properties of two objects using Java

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.