类实现Cloneable接口,然后用调用clone()方法,那么返回的只是一个浅拷贝的对象,基本属性的值是拷贝过来了而引用类型还是指向了被拷贝对象的引用类型。
方法一:类实现一个标记接口Serializable通过IO流来实现对象的深拷贝
public class Menus implements Serializable{
private static final long serialVersionUID = -5763470826096290328L;
private int num;
private List<String> list;
public Object deepClone() throws Exception {
// 将对象写到流里
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num = num;
}
public List<String> getList(){
return list;
}
public void setList(List<String> list){
this.list = list;
}
}
生成一个Menus对象,然后调用deepClone()方法就能获得一个深拷贝的Menus对象。
方法二:实现接口Cloneable
public class Menus implements Cloneable{
private int num;
private List<String> list;
@SuppressWarnings("unchecked")
@Override
protected Menus clone() throws CloneNotSupportedException{
Menus result = (Menus)super.clone();
result.list = ((List<String>)((ArrayList<String>)list).clone());
return result;
}
public int getNum(){
return num;
}
public void setNum(int num){
this.num = num;
}
public List<String> getList(){
return list;
}
public void setList(List<String> list){
this.list = list;
}
}
调用clone()方法生成一个克隆对象是没有调用构造函数的。