1.可以通过实现Cloneable接口并覆盖clone()方法来完成
public class Main implements Cloneable {
private List<String> items;
public Main() {
items = new ArrayList<>();
}
public void addItem(String item) {
items.add(item);
}
@Override
protected Main clone() throws CloneNotSupportedException {
Main cloned = (Main) super.clone();
// 深拷贝列表
cloned.items = new ArrayList<>(items);
return cloned;
}
public static void main(String[] args) throws CloneNotSupportedException {
Main original = new Main();
original.addItem("item1");
original.addItem("item2");
Main copy = original.clone();
copy.items.add("item3");
System.out.println(original.items); // 输出 [item1, item2]
System.out.println(copy.items); // 输出 [item1, item2, item3]
}
}
2.将对象转成json字符串,再构造新的对象
Person person = new Person()
String personJson = new Gson().toJson(person);
Person newPerson = new Gson().fromJson(personJson, Person.class);
注意:Person类需要实现Serializable接口
3.使用文件流序列化
public class ObjectDeepCopier {
public static <T extends Serializable> T deepCopy(T object) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
T deepCopy = null;
try {
// 序列化对象到byte数组
oos = new ObjectOutputStream(bos);
oos.writeObject(object);
oos.flush();
// 从byte数组反序列化对象
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
deepCopy = (T) ois.readObject();
} finally {
bos.close();
if (oos != null) oos.close();
if (ois != null) ois.close();
}
return deepCopy;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
// 示例对象
ExampleObject original = new ExampleObject(1, "original");
// 深拷贝对象
ExampleObject copy = deepCopy(original);
// 修改原始对象的属性,验证深拷贝
original.setValue(2);
original.setName("modified");
System.out.println("Original object: " + original);
System.out.println("Deep copied object: " + copy);
}
}
class ExampleObject implements Serializable {
private int value;
private String name;
public ExampleObject(int value, String name) {
this.value = value;
this.name = name;
}
public void setValue(int value) {
this.value = value;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "ExampleObject{" +
"value=" + value +
", name='" + name + '\'' +
'}';
}
}