How do you make a deep copy of an object in Java?

2018-12-31 03:37发布

In java it's a bit difficult to implement a deep object copy function. What steps you take to ensure the original object and the cloned one share no reference?

标签: java class clone
17条回答
其实,你不懂
2楼-- · 2018-12-31 03:54

For Spring Framework users. Using class org.springframework.util.SerializationUtils:

@SuppressWarnings("unchecked")
public static <T extends Serializable> T clone(T object) {
     return (T) SerializationUtils.deserialize(SerializationUtils.serialize(object));
}
查看更多
步步皆殇っ
3楼-- · 2018-12-31 03:56

Apache commons offers a fast way to deep clone an object.

My_Object object2= org.apache.commons.lang.SerializationUtils.clone(object1);
查看更多
萌妹纸的霸气范
4楼-- · 2018-12-31 03:56

Use XStream(http://x-stream.github.io/). You can even control which properties you can ignore through annotations or explicitly specifying the property name to XStream class. Moreover you do not need to implement clonable interface.

查看更多
笑指拈花
5楼-- · 2018-12-31 03:57
import com.thoughtworks.xstream.XStream;

public class deepCopy {
    private static  XStream xstream = new XStream();

    //serialize with Xstream them deserialize ...
    public static Object deepCopy(Object obj){
        return xstream.fromXML(xstream.toXML(obj));
    }
}
查看更多
牵手、夕阳
6楼-- · 2018-12-31 03:58

One very easy and simple approach is to use Jackson JSON to serialize complex Java Object to JSON and read it back.

http://wiki.fasterxml.com/JacksonInFiveMinutes

查看更多
若你有天会懂
7楼-- · 2018-12-31 04:00

Deep copying can only be done with each class's consent. If you have control over the class hierarchy then you can implement the clonable interface and implement the Clone method. Otherwise doing a deep copy is impossible to do safely because the object may also be sharing non-data resources (e.g. database connections). In general however deep copying is considered bad practice in the Java environment and should be avoided via the appropriate design practices.

查看更多
登录 后发表回答