groovy-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Paco Zarate <conta...@nazcasistemas.com>
Subject Re: Implementing DeepClone with Traits - Issue with groovyProxy
Date Thu, 28 May 2015 04:00:26 GMT
Hello,
I took your code and added the "as LinkedHashMap" when referring to "this"
(trying to take only the parent class, leaving out the trait itself):
//--- CODE STARTS ---//
trait DeepCloneable  {
    // implementation adapted from
http://stackoverflow.com/a/13155429/318102
    def deepClone() {
        def orig = (this as LinkedHashMap)
        def bos = new ByteArrayOutputStream()
        def oos = new ObjectOutputStream(bos)
        oos.writeObject(orig);
        oos.flush()
        def bin = new ByteArrayInputStream(bos.toByteArray())
        def ois = new ObjectInputStream(bin)
        return ois.readObject()
    }
}

def map = [list1: ["Fernando",  "Maria"], list2: ["Graciela",  "Alvaro"]]
as DeepCloneable
println "Original map:  " + map
def clone = map.deepClone()
println "DeepClone done."
println "clone:         " + clone

map['list3']= ["German", "Miriam"]
println "Modification on original map done."
println "Modified map:  " + map
println "clone:         " + clone
//--- CODE END ---//

Seems to be working.
I am not sure if this code is helpful for your use case this code:
//--- CODE STARTS --//
def map = [list1: ["Fernando",  "Maria"], list2: ["Graciela",  "Alvaro"]]
def clone = new LinkedHashMap(map)
//--- CODE END--//

Paco.

On Sun, May 10, 2015 at 11:39 AM, fniwes@gmail.com <fniwes@gmail.com> wrote:

> I am trying to implement a DeepClone using traits. I borrows the
> implementation from this stackoverflow answer
> <http://stackoverflow.com/a/13155429/318102>
>
> Is there a way to bypass the generated proxy? Or other implementation that
> can avoid this error? My simplistic test code is as follow
> (The real case is a map of lists, that's why I need a deep-clone)
>
> Thanks in advance.
>
> trait DeepCloneable {
>     // implementation adapted from
> http://stackoverflow.com/a/13155429/318102
>     def deepClone() {
>         def orig = this
>         def bos = new ByteArrayOutputStream()
>         def oos = new ObjectOutputStream(bos)
>         oos.writeObject(orig); oos.flush()
>         def bin = new ByteArrayInputStream(bos.toByteArray())
>         def ois = new ObjectInputStream(bin)
>         return ois.readObject()
>     }
> }
>
> def map = [name: "Fernando"] as DeepCloneable
> def clone = map.deepClone()
>
>

Mime
View raw message