Spring Ecology is in Java It is widely used in the project , From architecture to technology application to common basic functions ,Spring It brings great convenience to our development . Today, when we turn to the export report function in the project , Find ways to copy objects frequently :

 BeanUtils.copyProperties;

Assign the attribute value of the source object to the target object ,Spring and Apache And some other frameworks provide us with copy methods of object properties :

org.springframework.beans.BeanUtils.copyProperties(Object source, Object target)

org.apache.commons.beanutils.BeanUtils.copyProperties(Object dest, Object orig)

When using, pay attention to the parameter order of these two methods , The source and the target are opposite . Reflection is used in both methods , On a whim, I built my own wheel for copying objects , The code is as follows :

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap; public class ObjConvertor {
private static HashMap<String,HashMap<String,Method>> mapSetMethods=new HashMap<String,HashMap<String,Method>>();
private static HashMap<String,HashMap<String,Method>> mapGetMethods=new HashMap<String,HashMap<String,Method>>(); static
{ } public static boolean Convert(Object src,Object dst) {
HashMap<String,Method> mapSrc=new HashMap<String,Method>();
HashMap<String,Method> mapDst=new HashMap<String,Method>();
if(mapGetMethods.containsKey(src.getClass().getTypeName()))
mapSrc=mapGetMethods.get(src.getClass().getTypeName());
else
{
Method srcMethods[]=src.getClass().getMethods();
mapGetMethods.put(src.getClass().getTypeName(),mapSrc);
for(Method method:srcMethods)
{
String name=method.getName();
if(name.startsWith("get"))
{
String prop=name.substring(3).toLowerCase();
mapSrc.put(prop, method);
}
}
}
if(mapSetMethods.containsKey(dst.getClass().getTypeName()))
mapDst=mapSetMethods.get(dst.getClass().getTypeName());
else
{
Method dstMethods[]=dst.getClass().getMethods();
mapSetMethods.put(dst.getClass().getTypeName(),mapDst);
for(Method method:dstMethods)
{
String name=method.getName();
if(name.startsWith("set"))
{
String prop=name.substring(3).toLowerCase();
mapDst.put(prop, method);
}
}
}
for(String prop:mapSrc.keySet())
{
if(mapDst.containsKey(prop)){
Method setMethod=mapDst.get(prop);
Method getMethod=mapSrc.get(prop);
try {
Object data=getMethod.invoke(src);
if(data==null)
continue;
if(data instanceof java.sql.Time)
{
if(setMethod.getParameterTypes()[0]==String.class)
data=data.toString();
}
else if(data instanceof java.sql.Date)
{
if(setMethod.getParameterTypes()[0]==String.class)
data=new SimpleDateFormat("yyyy-MM-dd").format(data);
}
else if(data instanceof java.util.Date)
{
if(setMethod.getParameterTypes()[0]==String.class)
data=new SimpleDateFormat("yyyy-MM-dd").format((java.util.Date)data);
}
else if(data instanceof java.sql.Timestamp)
{
if(setMethod.getParameterTypes()[0]==String.class)
data=data.toString();
}
if(setMethod.getParameterTypes()[0]==java.sql.Time.class)
{
if(data instanceof String)
data=java.sql.Time.valueOf((String)data);
}
else if(setMethod.getParameterTypes()[0]==java.sql.Date.class)
{
if(data instanceof String)
data=java.sql.Date.valueOf((String)data);
}
else if(setMethod.getParameterTypes()[0]==java.util.Date.class)
{
if(data instanceof String)
{
data=(new SimpleDateFormat("yyyy-MM-dd")).parse((String)data);
}
}
else if(setMethod.getParameterTypes()[0]==java.sql.Timestamp.class)
{
if(data instanceof String)
data=java.sql.Timestamp.valueOf((String)data);
}
if(data==null)
continue;
setMethod.invoke(dst, data);
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
return true;
}
}

This is the end of the object copy function , If the project needs some special format data , Consider making your own wheels , It depends on the business needs .

Let's talk about object copying , If you are copying this object , Only the basic data types are copied , And the reference data type is just the transfer of reference , Instead of actually creating a new object , It's a shallow copy , such as Spring and Apache Of copyProperties And the copy method above . In turn, , When copying reference data types , Created a new object , And copy the member variables in it , It's a deep copy .

It's not difficult to find out by comparison : Deep copy creates a new object , It's just all the content of this object , It's as like as two peas , That is to say, the modification of the two is isolated , There is no influence on each other ; Shallow copy also creates an object , But something about this object ( such as A) It's still the copied object , That is, by modifying either of these two objects A, two-object A Will be affected .

Spring and Apache Of copyProperties They're all shallow copies , It can be used in daily development . It should be noted that , stay Java The development manual mentions , Not recommended for use Apache Of BeanUtils Tool class , Because there are a lot of tests 、 Type conversion 、 Log printing, etc , High implementation complexity , Poor performance .

So if we want to achieve high-performance and secure deep copy ? Deep copy means that all variables of the copied object have the same value as the original object , Remove variables that refer to other objects , Variables that refer to other objects will point to new objects that have been copied , Instead of trying the original referenced objects again , That is to say , Deep copy copies all the objects referenced by the object to be copied . I think the most reliable deep copy is to write stream after serialization , This approach needs to be implemented Serializable Interface , When you copy multiple copies , All reference types have to be implemented Serializable Interface . The code is as follows :

import java.io.*;
import java.util.Date; public class CopyDemo {
class User implements Serializable {
private int id;
private String username;// User name
private String sex;// Gender
private Date birthday;// Birthday
private String address;// Address
private Person person; // Reference type public User myColon(){
User copy=null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
// Sequence streams into objects
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
copy = (User) ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return copy;
} // Omit get-set method code
} class Person implements Serializable {
private int id;
private String userName ;
private int age ;
private String mobilePhone ;
public Person(){}
public Person(int id,String userName, int age, String mobilePhone) {
this.id = id;
this.userName = userName;
this.age = age;
this.mobilePhone = mobilePhone;
}
// Omit get-set Method
}
}

stay Java Deep copy of an object in a language , First, make the object implement Serializable Interface , And then put the object ( It's really just a copy of the object ) In a stream , Read it out of the stream , You can rebuild the object . You can see this process more clearly through the code . The process of writing objects into a stream is serialization (Serilization) The process , And reading objects out of the stream is parallelization (Deserialization) The process . It should be noted that , Objects that need to be copied may contain multiple reference types , Multi layer copy not only implements the serialization interface for the copy object , Reference objects also need to implement the serialization interface .

 

Java Copy the value of one object to another object in

  1. JAVA Get files from MD5 There are four ways to determine the value

    JAVA Get files from MD5 The four methods of value are very similar , Because the core is through JAVA Self contained MessageDigest Class to achieve . get files MD5 The value is mainly divided into three steps , The first step is to get the byte Information , The second step is to pass Messa ...

  2. Java Blocked and non-blocked IO Think about the advantages and disadvantages of each package ( classic )

    Java Blocked and non-blocked IO Think about the advantages and disadvantages of each package NIO The cornerstone of design : Reactor mode , Architecture patterns for event demultiplexing and dispatch . Reactor (Reactor): Architecture patterns for event demultiplexing and dispatch Usual , To a ...

  3. Java The problem of value passing and reference passing of parameter passing in ( turn )

    Today I met a java Program , You need parameters to return values ( Although in the end, it was realized in another way ), See such an article on the Internet , Very inspired . This article comes from http://hi.baidu.com/xzhilie/blog/item ...

  4. Java The default value of the initial variable in

    Java In language 8 Basic data types , The basic information is summarized as follows : Serial number data type size / position Wrapper class The default value is Can represent the data range 1 byte( position ) 8 Byte 0 -128~127 2 short( Short integer ) 16 ...

  5. JAVA in char and String/ Difference between value type and reference type

    import java.util.*; class test { public static void main(String[] args) { char a[] = {'b', 'a', 'c'} ...

  6. Java in Map According to the key value (key) Or worth it (value) Sort to achieve

    We all know ,java Medium Map Structure is key->value The key value pairs the stored , And according to Map Characteristics of , The same Map in There are no two Key Same element , and value There is no such limitation . let me put it another way , In the same Map in Ke ...

  7. Java in float/double Value range and precision

    Java Floating point numbers Floating point structure Make it clear Java The range and precision of floating point numbers , You must first understand the representation of floating point numbers , The structure of floating point numbers , The reason for this so-called structure , Because machines only know 01, You want to represent decimals , You need the machine to recognize the decimal point ...

  8. Java Call in MatLab Return value

    When in Java Use in MatLab Function time , Because of the difference of language grammar ,Matlab When multiple data are returned , Want to be in Java Get and use . Looking up the information on the Internet , Turn over the box and turn over the cabinet, plus your own actual combat , The conclusion is as follows : Such as MatLab Function returns N ...

  9. Java We have to talk about value passing and address passing

    Some personal knowledge , Hope to be able to learn Java you , Or if you're confused about passing method parameters, pray for a little help ! Here are some of the author's personal views , If there is a mistake , Welcome to point out your mistakes , Thanks for watching and supporting ... -------------- ...

  10. About Java Medium HashMap The test of the deep and shallow copy of and some thoughts on it

    0. Preface When the work gets busy , I haven't seen the algorithm for a long time , actually DFA Sensitive word algorithm must be optimistic for a while to understand ... It's the same as the third-order Rubik's cube reduction technique , The countryside will wither , It's a pity . stay DFA In the algorithm, , The first step is to understand its data structure , On this basis , involves ...

Random recommendation

  1. 【javaweb Study 】XML And constraint patterns

    xml: Extensible markup language ,w3c Published by the organization , Used to hold relational data , As a configuration file , Describe the relationship between program modules <?xml version="1.0" encoding="g ...

  2. alert Yes ajax Blocking the investigation (IE, Chrome, FF)

    I was conservative a while ago , To a js The effect has been improved , Because I am chrome If there is no problem in the next test, I will give it to my colleagues , Colleagues use FF, Found abnormal , Later I found out that js stay IE10 I can't do it , Had to investigate , Results found Chrome Of ale ...

  3. core-- process

    As we said earlier, a thread is a series of instructions , So what is the process ? A process is a container for these instructions . In addition to threads, the container , It also includes resources and so on . A process must have at least one thread . A process without a thread is not called a process " The difference between process and procedure : The process must be ...

  4. ###《Machine Learning》by Andrew NG

    Click to see Evernote original text . #@author: gr #@date: 2014-10-17 #@email: forgerui@gmail.com Fundamental One . Trace of matrix . Rank matrix ...

  5. The effect of turning books :FMX.TSwipeTransitionEffect Animation

    This example shows how to use a TSwipeTransitionEffect transition and a TPathAnimation to simulate t ...

  6. Learn to apply -----django Life cycle

    After listening to the explanation django After the video , Benefited greatly , Every knowledge point will be summarized by the teacher . Learn to summarize , Save it for your own use . django When the life cycle is understood , For the entire django There will be a clear understanding of . First map 1. The client sends the request , stay dj ...

  7. eclipse c++11 cmake gnuradio

    Take on the previous script . Modify the script code to make eclipse Use C++11 了 #!/bin/sh echo "creat_debug for sdk" echo "mkd ...

  8. js Five classic exercises -- The fourth way qq The friends list

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  9. The principle of strategy mode and Java Code instance

    One . Definition of strategy pattern —— A set of algorithms is defined , Package each algorithm , And make them interchangeable —— The policy pattern allows these algorithms to change without affecting each other when called by the client , Changing the implementation of different algorithms does not affect the use of the client , That's the policy ...

  10. Linux And Safety Practice II

    Linux And Safety Practice II   Basic kernel modules 20135238 Gong Rui 1.  Understand module principles linux A module is a collection of functions and data types that can be compiled as stand-alone programs . The reason why the module mechanism is provided , Because Linux Itself is a ...