Skip to content

Instantly share code, notes, and snippets.

@jp1017
Last active May 16, 2016 11:54
Show Gist options
  • Save jp1017/039d556db28f230e51204ba90c341791 to your computer and use it in GitHub Desktop.
Save jp1017/039d556db28f230e51204ba90c341791 to your computer and use it in GitHub Desktop.
Serializable 实现 java 深克隆: http://www.jianshu.com/p/c31e01a5d55d
public abstract class BeanUtils {
/**
* 只要要克隆的对象以及对象所包含的引用类型的成员对象所在的类实现了 java.io.Serializable 接口即可做到完美克隆。
*/
@SuppressWarnings("unchecked")
public static <T> T cloneTo(T src) throws RuntimeException {
ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
ObjectOutputStream out = null;
ObjectInputStream in = null;
T dist = null;
try {
out = new ObjectOutputStream(memoryBuffer);
out.writeObject(src);
out.flush();
in = new ObjectInputStream(new ByteArrayInputStream(memoryBuffer.toByteArray()));
dist = (T) in.readObject();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (out != null)
try {
out.close();
out = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
if (in != null)
try {
in.close();
in = null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return dist;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment