java 深复制对象,对象需要实现序列化接口

public static Object copy(Object obj) throws IOException, ClassNotFoundException
{
//写入对象到字节数组流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();

//从字节数组流中读取对象
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Object newObj = ois.readObject();

return newObj;
}

你可能感兴趣的:(java)