被拷贝对象一定要实现Serializable接口
public class DeepCloneUtil {
public static Object deepClone(Object obj){
Object copyObj=null;
try {
//对象序列化
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj);
//流序列化中取出对象
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
copyObj =ois.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return copyObj;
}
}
测试:
public class ObjCloneTest {
public static void main(String[] args){
Person p1=new Person();
p1.setName("1");
p1.setSex("男");
Person p2 = (Person) DeepCloneUtil.deepClone(p1);
p2.setName("2");
p2.setSex("女");
System.out.println(p1);
System.out.println(p2);
}
}