Last active
December 16, 2015 15:59
-
-
Save gythialy/a60af0ddcda7f26edbd4 to your computer and use it in GitHub Desktop.
DeepCopy object
This file contains 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
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