Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java deep copy library

Tags:

java

deep-copy

Is there library that can make deep copy?

ex) normal object, array, list, inputstream etc.

like image 709
yohei Avatar asked Feb 15 '11 07:02

yohei


People also ask

Does Java have deep copy?

Whenever you try to create a copy of an object, in the deep copy all fields of the original objects are copied exactly, in addition to this, if it contains any objects as fields then copy of those is also created (using the clone() method).

What does deep copy mean in Java?

Deep copy/ cloning is the process of creating exactly the independent duplicate objects in the heap memory and manually assigning the values of the second object where values are supposed to be copied is called deep cloning.

Is clone method a deep copy Java?

Apache Commons Lang has SerializationUtils#clone, which performs a deep copy when all classes in the object graph implement the Serializable interface.


2 Answers

@Konrad's posting is spot on. The only general way of doing deep copying is to use a Java serialization mechanism.

Obviously, it is expensive.

The other caveat is that some Java objects are impossible to copy by serialization. Examples include

  • Thread and subclasses cannot be serialized because a thread's execution state cannot be serialized.

  • Streams in general cannot be serialized because you cannot get at the state of the stream that has already been written (writers, output streams) or that is yet to be read (readers, input streams). (Indeed, in the reader / input stream case, that state may literally be infinite.)

  • GUI components cannot be serialized because they depend on the (external) graphics environment which can't be serialized.

like image 109
Stephen C Avatar answered Sep 28 '22 16:09

Stephen C


Look for serialization. Java supports it out of the box, but you can also try Hessian, Kryo...

Here's an introduction to Java serialization: http://java.sun.com/developer/technicalArticles/Programming/serialization/

And here's a benchmark done by the Kryo folks: http://code.google.com/p/thrift-protobuf-compare/wiki/Benchmarking (list of 20 serialization libs)

like image 36
Konrad Garus Avatar answered Sep 28 '22 17:09

Konrad Garus