java 深克隆clone物件或容器的另一種方法
阿新 • • 發佈:2018-12-03
本頁地址:http://blog.csdn.net/lpy3654321/article/details/43054557
java 深clone物件的另一種方法
public static <T> T deepCopy(T src) throws IOException, ClassNotFoundException{ ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(src); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in =new ObjectInputStream(byteIn); T dest = (T) in.readObject(); return dest; }
前提是,傳的物件,以及包含的物件需要都實現 java.io.Serializable 序列化 介面