有两种方式:
1). 实现 Cloneable 接口并重写 Object 类中的 clone()方法;
2). 实现 Serializable 接口,通过对象的序列化和反序列化实现克隆,可以实现真正的深度克隆,代码如下
@Data
public class MyObj implements Cloneable {
private String name;
private String age;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class CloneUtil {
private CloneUtil(){
throw new AssertionError();
}
public static <T extends Serializable> T clone(T obj) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (T)ois.readObject();
}
}
@Data
public class MyCat implements Serializable {
private String name;
private String age;
}
public class Test002 {
public static void main(String[] args) throws Exception {
MyObj myObj = new MyObj();
myObj.setAge("22");
MyObj clone = (MyObj)myObj.clone();
System.out.println(clone.getAge());
MyCat cat = new MyCat();
cat.setName("maomao");
MyCat clone1 = CloneUtil.clone(cat);
System.out.println(clone1.getName());
}
}