如何复制java
复制Java的方法
在Java中,复制对象或数组可以通过多种方式实现,具体取决于需求和上下文。
浅拷贝
浅拷贝仅复制对象的引用,而不复制对象本身。适用于基本数据类型或不可变对象。
int[] original = {1, 2, 3};
int[] copy = original.clone();
深拷贝
深拷贝会复制对象及其所有引用的对象。适用于包含可变对象的复杂结构。
class Person implements Cloneable {
String name;
Address address;
@Override
protected Object clone() throws CloneNotSupportedException {
Person cloned = (Person) super.clone();
cloned.address = (Address) address.clone();
return cloned;
}
}
使用序列化
通过序列化和反序列化实现深拷贝,适用于复杂对象图。
public static <T> T deepCopy(T object) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T) ois.readObject();
}
使用第三方库
Apache Commons Lang和Gson等库提供便捷的复制方法。
// Apache Commons Lang
Person copy = SerializationUtils.clone(original);
// Gson
Gson gson = new Gson();
Person copy = gson.fromJson(gson.toJson(original), Person.class);
手动复制
对于简单对象,可以手动创建新实例并复制字段。

Person copy = new Person();
copy.setName(original.getName());
copy.setAddress(new Address(original.getAddress()));
选择合适的方法取决于对象的复杂性和性能要求。浅拷贝适用于简单场景,深拷贝适用于嵌套对象,序列化和第三方库适用于复杂需求。






