在Java中,克隆對象的方法有以下幾種:
public class MyClass implements Cloneable {
private int value;
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
使用方式:
MyClass obj1 = new MyClass(10);
try {
MyClass obj2 = (MyClass) obj1.clone();
System.out.println(obj1.getValue()); // 輸出:10
System.out.println(obj2.getValue()); // 輸出:10
obj2.setValue(20);
System.out.println(obj1.getValue()); // 輸出:10
System.out.println(obj2.getValue()); // 輸出:20
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
public class MyClass {
private int value;
public MyClass(int value) {
this.value = value;
}
public MyClass(MyClass obj) {
this.value = obj.value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
使用方式:
MyClass obj1 = new MyClass(10);
MyClass obj2 = new MyClass(obj1);
System.out.println(obj1.getValue()); // 輸出:10
System.out.println(obj2.getValue()); // 輸出:10
obj2.setValue(20);
System.out.println(obj1.getValue()); // 輸出:10
System.out.println(obj2.getValue()); // 輸出:20
import java.io.*;
public class MyClass implements Serializable {
private int value;
public MyClass(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
使用方式:
MyClass obj1 = new MyClass(10);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj1);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
MyClass obj2 = (MyClass) ois.readObject();
System.out.println(obj1.getValue()); // 輸出:10
System.out.println(obj2.getValue()); // 輸出:10
obj2.setValue(20);
System.out.println(obj1.getValue()); // 輸出:10
System.out.println(obj2.getValue()); // 輸出:20
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
以上是常見的克隆對象的方法,根據具體的需求選擇適合的方法進行克隆。