1

I have a method to duplicate(clone) as below

static duplicateRecord(record)
{
    def copyRecord = [:]
    record.each{ fieldname, value ->
        if (value)
        {
            copyRecord [(fieldname)] = value?.clone()
        }
    }

    return copyRecord
}

Do we have any clone() method in Groovy/java to accomplish the same functionality ?

Techie
  • 1,611
  • 3
  • 15
  • 24

2 Answers2

0

I think you would need to implement the Cloneable interface. This post shows how to clone an object in Groovy without implementing the Cloneable interface, though I have not tested it.

ubiquibacon
  • 10,451
  • 28
  • 109
  • 179
0

This should do it.

Copied from: https://stackoverflow.com/a/13155429/889945

// standard deep copy implementation
def deepcopy(orig) {
     bos = new ByteArrayOutputStream()
     oos = new ObjectOutputStream(bos)
     oos.writeObject(orig); oos.flush()
     bin = new ByteArrayInputStream(bos.toByteArray())
     ois = new ObjectInputStream(bin)
     return ois.readObject()
}
Community
  • 1
  • 1
aayoubi
  • 11,285
  • 3
  • 22
  • 20
  • Silviu, you are right, though they could be added in `deepcopy`'s implementation. – aayoubi Sep 24 '13 at 15:12
  • 1
    You are right, however I just wanted to warn about the serialization process and its output. – Silviu Burcea Sep 24 '13 at 15:50
  • This will require all objects encountered to have classes that implement Serializable. If you need a true clone operation, use json-io (https://github.com/jdereg/json-io) with the following code: `JsonReader.jsonToJava(JsonWriter.objectToJson(root))` It won't require the objects to implement Serializable. As for including transients, those are marked as transient so as not to be included in serialization (that what transient means). However, if you really want to include them, you can - you can tell json-io for a given class what fields you want (if u want to control it at the field level) – John DeRegnaucourt Mar 12 '16 at 14:52