Translate

Thursday, August 13, 2015

Java DeepCopy using JAXB


import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import java.io.Serializable;

/** * Returns a deep copy of any object that implements Serializable. * This class uses JAXB to serialize and deserialize objects */public class Copier<T extends Serializable> {

    private final Class<T> type;

    public Copier(Class<T> type) {
        this.type = type;
    }

    public T GetCopy(T objectToBeCopied) {

        JAXBElement<T> serializedObject = new JAXBElement(new QName("T"), type, objectToBeCopied);

        T deserialized = serializedObject.getValue();

        return (T) (deserialized);

    }


}



Example that uses the code4 above

Copier<Person> copier =new Copier(Person.class);
Person deepCopyPerson= copier.GetCopy(myPerson); 

No comments:

Post a Comment

Comments will appear once they have been approved by the moderator