java如何拷贝
深拷贝与浅拷贝的概念
在Java中,拷贝分为浅拷贝和深拷贝。
- 浅拷贝:复制对象时,仅复制对象的引用(如成员变量为对象时,复制的是地址),原对象和拷贝对象共享内部对象。
- 深拷贝:完全复制对象及其引用的所有对象,生成一个完全独立的副本。
实现浅拷贝的方法
-
Object.clone()方法
类需实现Cloneable接口并重写clone()方法:class Example implements Cloneable { int value; Object ref; @Override public Object clone() throws CloneNotSupportedException { return super.clone(); // 默认浅拷贝 } } -
通过构造方法或工厂方法
手动复制字段值:class Example { int value; Object ref; Example(Example other) { this.value = other.value; this.ref = other.ref; // 浅拷贝引用 } }
实现深拷贝的方法
-
递归调用
clone()
对引用类型字段也实现Cloneable并调用其clone()方法:class DeepExample implements Cloneable { int value; Object ref; @Override public Object clone() throws CloneNotSupportedException { DeepExample copy = (DeepExample) super.clone(); copy.ref = new Object(); // 深拷贝:创建新对象 return copy; } } -
序列化与反序列化
通过ObjectOutputStream和ObjectInputStream实现完全深拷贝:import java.io.*; class SerializableExample implements Serializable { int value; Object ref; public SerializableExample deepCopy() throws IOException, ClassNotFoundException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (SerializableExample) ois.readObject(); } } -
第三方库工具
使用Apache Commons Lang的SerializationUtils:
import org.apache.commons.lang3.SerializationUtils; SerializableExample original = new SerializableExample(); SerializableExample copy = SerializationUtils.clone(original);
注意事项
- 不可变对象(如
String、基本类型包装类)无需深拷贝,因其本身不可变。 - 性能权衡:深拷贝可能因递归或序列化导致较高开销,需根据场景选择。
- 循环引用:深拷贝时需处理对象间的循环引用,避免栈溢出。






