在Java中,要克隆一個實體類對象,可以使用以下三種方法:
public class MyClass implements Cloneable {
private int id;
private String name;
// constructor, getter, setter methods
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
使用時可以調用對象的clone()方法來實現克隆:
MyClass obj1 = new MyClass();
MyClass obj2 = (MyClass) obj1.clone();
public class MyClass {
private int id;
private String name;
public MyClass(MyClass obj) {
this.id = obj.id;
this.name = obj.name;
}
// getter, setter methods
}
使用時可以通過調用構造方法進行克隆:
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass(obj1);
public class MyClass implements Serializable {
// fields and methods
}
使用時可以通過序列化和反序列化進行克隆:
MyClass obj1 = new MyClass();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj1);
oos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
MyClass obj2 = (MyClass) ois.readObject();