Use Java to copy the attributes of two objects

Source: Internet
Author: User

Use Java to copy the attributes of two objects

Recently, I have been dealing with Java reflection a little more, probably because I will focus on architects in the future. They are mainly engaged in business. I can also build the architecture and draw some flowcharts throughout the day.

Although I have only one year of practical experience, I don't know whether this is good or not, but I am still saying that, whether it is good or bad, I can learn a lot after all, you can also exercise your own thinking skills.

Expressive ability, because your product is doing well, you just cannot express it, you cannot say it, then you will lose.

Create an object class User first

Package com. mine. practice. copyproperty. entity;/***** @ author 10:28:10 * @ version V1.0 */public class User {private int id; private String name; private String pwd; private double idG; public double getIdG () {return 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 the specific copy has been tested.

Package com. mine. practice. copyproperty. test; import java. lang. reflect. field; import com. mine. practice. copyproperty. entity. user;/*** copy properties * @ author 10:29:32 */public class TestCopyProperty {/*** business requirements: * When updating data of one or more classes for some businesses, you only want to update some fields of the class. Other fields also use the previous values. ** Problems: * when some businesses need to increase or decrease the number of fields of a class and modify the field name, the front-end may only need to modify one place to solve the problem. * However, the background uses the event processing method, so it may be used in multiple places, making it difficult to modify it. ** Main solution: * The background Code does not need to be modified even after the number of fields or field name is modified. ** Solution: * The solution is modified based on the previous solution. * Traverse all attributes of the class and obtain the attribute values of the new class, if the attribute value of the new class is not null, an empty string, or the default value of the basic type *, the new object attribute value is assigned to the old object attribute. ** advantages: 1. You do not need to change the background even if you add or modify the number of fields * 2. You do not need to change the background even if you modify the field name or type. ** disadvantages: 1. it traverses all attributes of a class and determines whether the new object's property value exists and whether it is the default value. Batch Data performance may be somewhat poor * 2. Because the basic data type has a default value, the Framework does not know whether to change the value of this field to a new object. * ** @ Author 11:01:03 * @ param args * @ throws SecurityException * @ throws NoSuchFieldException * @ throws syntax * @ throws IllegalAccessException * @ modificationHistory ====== =================== logical or functional major change records * @ modify by user: {modifier} 2014-11-6 * @ modify by reason: {cause} */public static void main (String [] args) throws SecurityException, NoSuchFieldException, IllegalArgument Exception, IllegalAccessException {// old Object User oldUser = new User (); oldUser. setId (1); oldUser. setName ("name1"); oldUser. setPwd ("pwd1"); oldUser. setIdG (1.2); System. out. println ("old objects in the Database"); print (oldUser); // new Object User newUser = new User (); newUser. setName ("name2"); System. out. println ("new objects passed in the foreground"); print (newUser); // functional requirements // modify the id and name of the previous old object, however, pwd does not need to modify copyProperty (oldUser, newUser); System. out. println ("---------- old pair Like --------------- "); print (oldUser );} /***** @ author 11:26:36 * @ param oldUser * @ param newUser * @ throws NoSuchFieldException * @ throws SecurityException * @ throws syntax * @ modificationHistory = ==================================== records of major logical or functional changes * @ modify by user: {modifier} 2014-11-6 * @ modify by reason: {reason} */@ SuppressWarnings ("rawtypes") private static Void copyProperty (User oldUser, User newUser) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {// new classClass newClass = newUser. getClass (); // The old classClass oldClass = oldUser. getClass (); // all attributes of this class Field [] newFields = newClass. getDeclaredFields (); // new attribute Field newField = null; // old attribute Field oldField = null; for (Field f: newFields) {// attribute name in the class String fieldName = F. getName (); // obtain the attribute newField = newClass by using the attribute name. getDeclaredField (fieldName); // if you need to set the attribute value to true, it indicates that the reflected object should cancel the Java language access check during use. // If the value is false, it indicates that the reflected object should implement Java access check. NewField. setAccessible (true); // obtain the value of Object newObject = newField Based on the attribute. get (newUser); // filter empty attributes or some default values if (isContinue (newObject) {continue;} oldField = oldClass. getDeclaredField (fieldName); oldField. setAccessible (true); oldField. set (oldUser, newObject );}} /*** do you want to skip this loop? * @ author 11:37:22 * @ param object * @ return true: null or default * false/default */private 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 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 ());}}

Simple functions, but I learned some new knowledge.

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.