java 对象序列化实现深拷贝的核心做法是:将对象写入字节流再读回新对象,从而获得完全独立的副本。具体操作需让类实现 serializable 接口,并通过 objectoutputstream 和 objectinputstream 完成转换。此方法会自动处理嵌套对象的引用关系,确保修改副本不会影响原对象。

Serializable 接口的必要性是什么
必须实现 Serializable 接口才能触发序列化机制。该接口是一个标记接口,不包含任何方法,仅用于告知 JVM 该类实例可以被转换为字节序列。若未实现此接口而尝试序列化,会抛出 NotSerializableException。此外,所有非静态字段所属的类也必须可序列化,否则同样会失败。

import java.io.*;
public class DeepCopyExample implements Serializable {
private String name;
private int age;
public DeepCopyExample(String name, int age) {
this.name = name;
this.age = age;
}
public static DeepCopyExample deepCopy(DeepCopyExample original) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(original);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
DeepCopyExample copy = (DeepCopyExample) ois.readObject();
ois.close();
return copy;
}
public static void main(String[] args) throws Exception {
DeepCopyExample original = new DeepCopyExample("Alice", 30);
DeepCopyExample copy = deepCopy(original);
System.out.println(original == copy); // false
System.out.println(copy.getName()); // Alice
}
}如何处理不可序列化的字段
如果类中包含无法序列化的字段(如 Thread、Socket 或自定义非 Serializable 对象),直接序列化会失败。解决方案是使用 transient 关键字修饰这些字段,使其在序列化时被忽略。在反序列化后,这些字段将为默认值(null 或 0)。若需恢复这些字段,可重写 readObject 方法手动初始化,或在反序列化后通过其他逻辑重新赋值。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。
立即学习“Java免费学习笔记(深入)”;

import java.io.*;
public class TransientExample implements Serializable {
private String id;
private transient String sensitiveData; // 被忽略
public TransientExample(String id, String sensitiveData) {
this.id = id;
this.sensitiveData = sensitiveData;
}
public static TransientExample deepCopy(TransientExample original) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(original);
oos.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
TransientExample copy = (TransientExample) ois.readObject();
ois.close();
return copy;
}
public static void main(String[] args) throws Exception {
TransientExample original = new TransientExample("123", "secret");
TransientExample copy = deepCopy(original);
System.out.println(copy.sensitiveData); // null
}
}序列化深拷贝在并发场景下是否安全
序列化深拷贝生成的对象是完全独立的,因此不存在共享状态导致的并发问题。每个副本拥有自己的内存空间,对副本的修改不会反映到原对象或其他副本上。这使得它在需要创建线程安全快照的场景中非常有用,例如在多线程环境中保存某个时刻的对象状态供后续分析,而无需加锁保护原对象。

















