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?
I've run benchmarks on various solutions for cloning a JAXB object. Here are some results:
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).
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();
}
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With