有以下几种方法可以拷贝一个对象:
public class MyClass {
private int value;
public MyClass(MyClass original) {
this.value = original.value;
}
// getters and setters
}
public class MyClass implements Cloneable {
private int value;
@Override
public MyClass clone() {
try {
return (MyClass) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
// getters and setters
}
import java.io.*;
public class MyClass implements Serializable {
private int value;
public MyClass deepClone() {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (MyClass) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
return null;
}
}
// getters and setters
}
这三种方法都可以用来拷贝一个对象,根据具体的需求和情况选择适合的方法进行拷贝。