Last active
May 16, 2016 11:54
-
-
Save jp1017/039d556db28f230e51204ba90c341791 to your computer and use it in GitHub Desktop.
Serializable 实现 java 深克隆: http://www.jianshu.com/p/c31e01a5d55d
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
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