5

Is there library that can make deep copy?

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

palacsint
  • 28,416
  • 10
  • 82
  • 109
yohei
  • 51
  • 1
  • 2
  • http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java – palacsint May 22 '12 at 11:07
  • Kryo has built-in support for [copying/cloning](https://code.google.com/p/kryo/#Copying/cloning). This is direct copying from object to object, not object->bytes->object. – NateS Jun 15 '12 at 02:41

5 Answers5

6

@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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
4

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)

Konrad Garus
  • 53,145
  • 43
  • 157
  • 230
  • 1
    quick comment: afaik, benchmark is not done just by kryo author, but by group of folks -- that is, being collective work, it should be less subjective than benchmarks by any single author. Esp. since multiple "competing" authors contribute to benchmark, which helps keep everyone honest. – StaxMan Mar 09 '11 at 22:43
3

Maybe you can have a look at Dozer.

1
  1. For small objects: copy constructor.
  2. For large objects, whose member references are having tree like structure, go for java serialization.
palacsint
  • 28,416
  • 10
  • 82
  • 109
Dead Programmer
  • 12,427
  • 23
  • 80
  • 112
0

There is a small library that makes it possible to do deep cloning as well as shallow cloning. This answer contains much more details.

dilanSachi
  • 562
  • 6
  • 14