Skip to content

Instantly share code, notes, and snippets.

@darrend
Created February 10, 2011 21:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save darrend/821410 to your computer and use it in GitHub Desktop.
Save darrend/821410 to your computer and use it in GitHub Desktop.
deep copy an object using jaxb
public static <T> T deepCopyJAXB(T object, Class<T> clazz) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
JAXBElement<T> contentObject = new JAXBElement<T>(new QName(clazz.getSimpleName()), clazz, object);
JAXBSource source = new JAXBSource(jaxbContext, contentObject);
return jaxbContext.createUnmarshaller().unmarshal(source, clazz).getValue();
} catch (JAXBException e) {
throw new RuntimeException(e);
}
}
public static <T> T deepCopyJAXB(T object) {
if(object==null) throw new RuntimeException("Can't guess at class");
return deepCopyJAXB(object, (Class<T>) object.getClass());
}
@renganathan
Copy link

Thanks a lot! It really helps

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment