Spring - Java Object Clone

import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/*
* This class provides methods to copy properties from on object to another
*/
public class JavaObjectClone {

       
        public static <T> T deepCopy(T object,Class<T> aClass) throws ClassNotFoundException, IOException{
                ByteArrayOutputStream bOut = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(bOut);
                oos.writeObject(object);
                oos.close();
               
                ByteArrayInputStream bis = new ByteArrayInputStream(bOut.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bis);
               
                return aClass.cast(ois.readObject());
        }
       
                public static <T> void copy(T src, T dest, String... properties) {
                final BeanWrapper source = new BeanWrapperImpl(src);
                final BeanWrapper target = new BeanWrapperImpl(dest);
                for (final String propertyName : properties) {
                        target.setPropertyValue(
                                        propertyName,
                                        source.getPropertyValue(propertyName)
                                        );
                }
        }

}

Technology: 

Search