一、前言
通过java.io.ObjectInputStream/java.io.ObjectOutputStream对象写入写出流定义DeepClone深度复制类,实现对象深度克隆cloneObject复制,详情代码示例说明。
二、代码示例
package test;@b@@b@import java.io.ByteArrayInputStream;@b@import java.io.ByteArrayOutputStream;@b@import java.io.ObjectInputStream;@b@import java.io.ObjectOutputStream;@b@import java.io.Serializable;@b@@b@public class DeepClone {@b@@b@ public static Object cloneObject(Object obj) throws Exception {@b@ @b@ ByteArrayOutputStream byteOut = new ByteArrayOutputStream();@b@ ObjectOutputStream out = new ObjectOutputStream(byteOut);@b@ out.writeObject(obj);@b@@b@ ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());@b@ ObjectInputStream in = new ObjectInputStream(byteIn);@b@ return in.readObject();@b@ }@b@ @b@ public static <T> T cloneObject2(T orig) throws IOException, ClassNotFoundException {@b@ ByteArrayOutputStream bos = new ByteArrayOutputStream();@b@ ObjectOutputStream oos = new ObjectOutputStream(bos);@b@ oos.writeObject(orig);@b@ oos.flush();@b@ ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());@b@ ObjectInputStream ois = new ObjectInputStream(bin);@b@ return (T)ois.readObject();@b@ }@b@ @b@ public static class ClassDTO implements Serializable{@b@ @b@ private String no;@b@ private String cName;@b@ @b@ public ClassDTO(String no, String cName) {@b@ super();@b@ this.no = no;@b@ this.cName = cName;@b@ }@b@@b@ @Override@b@ public String toString() {@b@ return this.getClass().getName()+"@【no="+no+";cName="+cName+";hashCode="+this.hashCode()+"】";@b@ }@b@ @b@ }@b@@b@ public static void main(String[] args) throws Exception{@b@ @b@ ClassDTO sourceCla=new ClassDTO("601","六年级一班");@b@ System.out.println("【sourceCla】"+sourceCla.toString());@b@ @b@ ClassDTO targetCla=(ClassDTO)cloneObject(sourceCla);@b@ System.out.println("【targetCla】"+targetCla.toString());@b@@b@ }@b@@b@}
控制台输入结果
【sourceCla】test.DeepClone$ClassDTO@【no=601;cName=六年级一班;hashCode=827574】@b@【targetCla】test.DeepClone$ClassDTO@【no=601;cName=六年级一班;hashCode=8918002】