Created
May 19, 2011 19:49
-
-
Save darrend/981576 to your computer and use it in GitHub Desktop.
using jaxb to create deepcopies of objects, and build them from strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.xml.bind.*; | |
import javax.xml.bind.util.JAXBSource; | |
import javax.xml.namespace.QName; | |
import javax.xml.transform.stream.StreamSource; | |
public class DeepCopier<T> { | |
private static QName qname = new QName("deepcopy"); | |
private Unmarshaller unmarshaller; | |
private JAXBElement<T> contentObject; | |
private Marshaller marshaller; | |
private Class<T> clazz; | |
public DeepCopier(Class<T> clazz) { | |
this.clazz = clazz; | |
contentObject = new JAXBElement<T>(qname, clazz, null); | |
try { | |
JAXBContext jaxbContext = JAXBContext.newInstance(clazz); | |
unmarshaller = jaxbContext.createUnmarshaller(); | |
marshaller = jaxbContext.createMarshaller(); | |
} catch(JAXBException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public T deepCopy(T object) { | |
if(object==null) return null; | |
contentObject.setValue(object); | |
try { | |
return unmarshaller.unmarshal(new JAXBSource(marshaller,contentObject),clazz).getValue(); | |
} catch (JAXBException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
/* | |
new DeepCopier<XMLGregorianCalendar>(XMLGregorianCalendar.class).readXML(new StreamSource(new StringReader(new StringBuilder().append("<x>").append(time).append("2010-08-25T09:26:00").toString()))); | |
*/ | |
public T readXML(StreamSource source) throws JAXBException { | |
JAXBElement<T> root = unmarshaller.unmarshal(source, clazz); | |
return root.getValue(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment