Several methods of java copying objects

Recently, business has to copy objects, but I don't want to get and set one by one, so I found three methods to copy objects online.
One, shallow copy.
1. The class that needs to be copied implements the Cloneable interface;
2. Overwrite the clone () method;
import java.lang.Cloneable ;;

public class OrderVO implements Cloneable {

private int orderID;

private int userID;

private double orderAmount;

public int getOrderID() {
	return orderID;
}

public void setOrderID(int orderID) {
	this.orderID = orderID;
}

public int getUserID() {
	return userID;
}

public void setUserID(int userID) {
	this.userID = userID;
}

public double getOrderAmount() {
	return orderAmount;
}

public void setOrderAmount(double orderAmount) {
	this.orderAmount = orderAmount;
}

@Override
public Object clone() {
	OrderVO vo = null;
	try {
	vo = (OrderVO) this.clone();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return vo;
	
}

}
Second, deep copy.
In shallow copy, only member variables of value type, for reference types, copy the address of the reference object to the clone object, that is to say, the member variables of the prototype object and the clone object point to the same memory address. In this way, the reference value of the copied object is modified, and the value of the original object will also change, which is of course wrong.
There are two solutions, one is to set the reference type of the variable to the clone object; the second is to directly implement serialization, perform IO operations on the object, and read / write. One can imagine that method one is more troublesome.
Third, the tool class BeanUtils and PropertyUtils for object replication
Whether it is to implement the clone () method, or IO operation, is more troublesome, and the code is too much. At this time, you can use java tool class, get it in one line.
The main difference between BeanUtils and PropertyUtils is that BeanUtils provides type conversion function, that is, when it is found that two JavaBeans with the same name attribute are different types, conversion is performed within the range of supported data types, but PropertyUtils does not support this function. Because it is not supported, the speed will be faster. In actual development, BeanUtils is more commonly used and the risk of making mistakes is lower.

    OrderVO vo1 = new OrderVO(); // 原对象
	OrderVO vo2 = new OrderVO(); // 目标对象
	try {
		BeanUtils.copyProperties(vo2, vo1);
	} catch (Exception e) {
		e.printStackTrace();
	}

Note that if you want to copy objects in a loop, you must not write the statement of new new object outside the loop, otherwise each new value is a reference address.

Published 6 original articles · liked 0 · visits 354

Guess you like

Origin blog.csdn.net/weixin_44863376/article/details/105453562