在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();