序列化 Serialization

利用序列化实现深度克隆

  把对象写到流里的过程是序列化(Serialization)过程;而把对象从流中读出来的过程则叫反序列化(Deserialization)过程。应当指出的是,写到流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。

  在Java语言里深度克隆一个对象,常常可以先使对象实现Serializable接口,然后把对象(实际上只是对象的拷贝)写到一个流里(序列化),再从流里读回来(反序列化),便可以重建对象。

[java]  view plain copy print ?
  1. public  Object deepClone() throws IOException, ClassNotFoundException{  
  2.         //将对象写到流里  
  3.         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
  4.         ObjectOutputStream oos = new ObjectOutputStream(bos);  
  5.         oos.writeObject(this);  
  6.         //从流里读回来  
  7.         ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());  
  8.         ObjectInputStream ois = new ObjectInputStream(bis);  
  9.         return ois.readObject();  
  10.     }  

猜你喜欢

转载自meteor-1988.iteye.com/blog/1746053
今日推荐