序列化:其实就是相当于把一个对象变成字节流
反序列化:就是把一个字节流重构成对象
这样就可以把对象进行数据持久性保存到文件中去,或者从文件中导出对象使用了
一.Java的使用案例为利用ObjectOutputStream 和 ObjectInputStream进行读写对象,好处就是不用调用数据库也可以使对象持久化存储
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path));
Person person = new Person();
person.setName("小郑");
person.setAge(20);
outputStream.writeObject(person);
outputStream.close();
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(path));
Object object = inputStream.readObject();
System.out.println(object);
inputStream.close();
说明:要进行读写的对象必须实现Serializable接口
注意:字节流写进的文件都是乱码
运行结果:
二.序列化的注意事项
1.static关键字:静态关键字
静态优先于非静态加载到内存中(静态优先于对象进入到内存中)
序列化的都是对象,因此被static修饰的成员变量是不能被序列化(static修饰的成员变量反序列化后读取到的都是默认值)
例:
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path));
Person person = new Person();
person.setName("小郑");
person.setAge(20);
person.setTestStr("测试");
outputStream.writeObject(person);
outputStream.close();
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(path));
Object object = inputStream.readObject();
Person person1 = (Person) object;
System.out.println(person1.getName() + person1.getAge() + person1.getTestStr() );
inputStream.close();
运行结果:
这里测试结果值可以跑出来是因为:
transient 和 static 都没序列化到文件中,但是给 static 赋值后已经存到全局变量里了,反序列化时,文件中没有 transient 的成员变量的值,就是默认值,static 与 对象无关,跟类有关。
序列化与static的关系可以参考:
https://blog.csdn.net/yangxiangyuibm/article/details/43227457
会比较详细一点
三. transient关键字:瞬态关键字
被transient关键字修饰的对象不可以被序列化
例:
代码跟上面一样
运行结果:
四.每次序列化后要是序列化的类做出了改动的话,反序列化就会报错,如下
原因:每次改动都会生成一个新的ID,而这个ID就是反序列时所需要的相对应的ID
解决方案:
为每个序列化的类增加一个静态字段
static final long serialVersionUID
static final long serializ = 1L;