java如何拷贝值
拷贝值的方法
在Java中,拷贝值可以分为浅拷贝和深拷贝两种方式。浅拷贝仅复制对象的引用,而深拷贝会复制对象及其所有引用的对象。以下是几种常见的实现方法。
浅拷贝的实现
使用clone()方法可以实现浅拷贝。需要实现Cloneable接口并重写clone()方法。
class Person implements Cloneable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
调用clone()方法时,对象的基本类型字段会被复制,但引用类型字段仅复制引用。

深拷贝的实现
深拷贝需要手动复制所有引用类型的字段。可以通过递归调用clone()方法或序列化实现。
方法一:递归调用clone()
class Address implements Cloneable {
private String city;
public Address(String city) {
this.city = city;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Person implements Cloneable {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
cloned.address = (Address) address.clone();
return cloned;
}
}
方法二:序列化实现深拷贝
通过序列化和反序列化实现深拷贝,确保所有引用对象都被复制。

import java.io.*;
class Person implements Serializable {
private String name;
private Address address;
public Person(String name, Address address) {
this.name = name;
this.address = address;
}
public Person 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 (Person) ois.readObject();
}
}
使用构造方法或工厂方法
通过构造方法或工厂方法手动复制字段值也是一种常见的拷贝方式。
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}
使用第三方库
Apache Commons Lang库提供了SerializationUtils.clone()方法,可以简化深拷贝的实现。
import org.apache.commons.lang3.SerializationUtils;
Person original = new Person("Alice", 25);
Person copied = SerializationUtils.clone(original);
注意事项
- 浅拷贝仅复制引用,修改拷贝对象的引用字段会影响原对象。
- 深拷贝会复制所有引用对象,但可能带来性能开销。
- 序列化方式要求所有相关类实现
Serializable接口。






