利用序列化将Java对象深拷贝


public Object deepClone() throws IOException, OptionalDataException,  
        ClassNotFoundException {  
    // 将对象写到流里  
    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());  

对象所属的类要实现Serializable接口。同时将该方法写入到对象所属的类中。

深拷贝的时候,调用该方法即可。

 

相关内容