在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();
}
以上是常见的克隆对象的方法,根据具体的需求选择适合的方法进行克隆。