1. 克隆有三种方法:
1) 实现Cloneable接口,重写他的clone()方法。
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
2) 使用BeanUtils类的方法。
a) BeanUtils.copyProperties(desObject, srcObject);将源对像srcObject克隆一分给desObject
b) BeanUtils.cloneBean(object);克隆一个对像
以上1)和2)两种方法都只能是浅层克隆,也就是说对像里存在对像时子对像不会被克隆。
3) 对像序列化,不管主类中嵌套有多深,都可以实现深层拷贝:
public static Object clone(Object obj) throws Exception {
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream(byteOut);
outStream.writeObject(obj);
ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
ObjectInputStream inStream = new ObjectInputStream(byteIn);
return inStream.readObject();
}