Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Clone A JAXB Object

Tags:

java

jaxb

I have some jaxb objects (instantiated from code generated from xsd by jaxb) that I need to clone. The Jaxb class does not appear to provide an interface for doing this easily. I can not hand edit the class and can not extend it - so I need to create a helper/utility method to do this. What is the best approach?

like image 480
Shane C. Mason Avatar asked May 30 '09 23:05

Shane C. Mason


1 Answers

I've run benchmarks on various solutions for cloning a JAXB object. Here are some results:

  1. Using mofokom's xjc-clone plugin seems to be the fastest solution. It just lets all your generated artefacts implement Cloneable and publicly overrides Object.clone(). Unfortunately, this hasn't made it into Maven central (yet).

  2. Generating Serializable artefacts and serialising / deserialising them to a dummy stream is 10x slower than using Java's cloning mechanisms:

    public <T extends Serializable> T clone(T jaxbObject) {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      ObjectOutputStream o = new ObjectOutputStream(out);
      o.writeObject(jaxbObject);
      o.flush();
    
      ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
      ObjectInputStream i = new ObjectInputStream(in);
      return (T) i.readObject();
    }
    
  3. Marshalling / Unmarshalling the JAXB objects is again 5x slower than serialising / deserialising them. This is what ykaganovich's solution suggests:

    public <T extends Serializable> T clone(T jaxbObject) {
      StringWriter xml = new StringWriter();
      JAXB.marshal(jaxbObject, xml);
      StringReader reader = new StringReader(xml.toString());
      return JAXB.unmarshal(reader, jaxbObject.getClass());
    }
    
like image 91
Lukas Eder Avatar answered Oct 08 '22 11:10

Lukas Eder