Skip to content

Instantly share code, notes, and snippets.

@gythialy
Last active December 16, 2015 15:59
Show Gist options
  • Save gythialy/a60af0ddcda7f26edbd4 to your computer and use it in GitHub Desktop.
Save gythialy/a60af0ddcda7f26edbd4 to your computer and use it in GitHub Desktop.
DeepCopy object
package com.clone;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.nutz.castor.Castors;
public class DeepCopy {
/**
* Returns a copy of the object, or null if the object cannot be serialized.
*/
public static <T> T clone(Object orig, Class<T> clazz) {
Object obj = null;
try (FastByteArrayOutputStream fbos = new FastByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(fbos);) {
out.writeObject(orig);
out.flush();
ObjectInputStream in = new ObjectInputStream(fbos.getInputStream());
obj = in.readObject();
in.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return obj == null ? null : Castors.me().castTo(obj, clazz);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment