序列化和反序列化

序列化和反序列化

  1. 什么是序列化和反序列化

序列化 Serialization  将对象的状态信息转换为可以存储或传输的形式的过程。对象(内存)------->字节数组  字节序列(外存、网络)

反序列化:DeSerialization  

字节数组  字节序列(外存、网络)----------->对象(内存)

  

  1. 什么时候需要序列化和反序列化

  存储或传输 比如存储到外存(硬盘)中   传输到网络

 

  1. 如何实现序列化和反序列化

  相应的类要实现Serializable接口 

 

 public class Student implements Serializable {

}

 

ObjectOutputStream oos = new ObjectOutputStream(bos);

oos.writeObject(new Student(1, "111", 22, 333.3));

ObjectInputStream ois = new ObjectInputStream(bis);

Student stu = (Student)ois.readObject();

  1. 序列化的细节
  • 为什么序列化接口没有任何方法,哪还有什么用

 (查看ObjectOutputStream源码)

  • static属性不参与序列化
  • 如果不希望某个属性参与序列化,要使用transient修饰
  • Exception in thread "main" java.io.InvalidClassException:

com.bjsxt.entity.Student; local class incompatible:

stream classdesc serialVersionUID = 5954363181006202290,

local class serialVersionUID = -1877375566195009060  

解决方案:给出一个固定的序列化版本号

  • 使用对象流把一个对象写到文件时不仅保证该对象是序列化的,而且该对象的成员对象也必须是可序列化的。

 

posted @ 2021-01-07 12:22  巧克力曲奇  阅读(98)  评论(0编辑  收藏  举报