public static Object deepClone(Object object) {
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(object);
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
return objectInputStream.readObject();
} catch (Exception e) {
log.error("clone object error:" + e.getMessage());
throw new IllegalStateException(e);
} finally {
try {
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (objectInputStream != null) {
objectInputStream.close();
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
java 反序列化深度克隆Object
最新推荐文章于 2025-09-12 14:34:11 发布
本文介绍了一种通过序列化方式实现Java对象深克隆的方法。该方法利用了ByteArrayOutputStream、ObjectOutputStream、ByteArrayInputStream和ObjectInputStream等类来完成对象的复制过程。首先将对象写入字节数组中,然后从字节数组中读取对象,从而得到一个与原对象内容完全相同的副本。
1369

被折叠的 条评论
为什么被折叠?



