java序列化与反序列化
程序员文章站
2022-07-02 12:22:20
Java序列化(创建可复用的Java对象) 保持(持久化)对象及其状态到内存或磁盘 Java平台允许我们在内存中创建可复用的Java对象,但一般情况下,只有当JVM处于运行时,这些对象才可能存在,即这些对象的生命周期不会比JVM的生命周期更长。但在现实应用中,就可能要求在JVM停止运行之后能够保存( ......
1.定义
- 序列化:将java对象转换为二进制字节流
- 反序列化:将二进制字节流转换为java对象
2.实现序列化的方式
- 实现Serializable接口(transient关键字修饰的字段不会被序列化和反序列化)
3.序列化和反序列化测试
package com.example.demo.srializable;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.Serializable;
@Getter
@Setter
@ToString
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private transient String id;
private String name;
private String sex;
private int age;
}
public static void main(String[] args) throws Exception {
User user = new User();
user.setId("1");
user.setName("张三");
user.setSex("男");
user.setAge(20);
System.out.println(user);
ObjectOutputStream objectOutputStream = null;
ObjectInputStream objectInputStream = null;
try {
objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("D://User")));
objectOutputStream.writeObject(user);
objectInputStream = new ObjectInputStream(new FileInputStream(new File("D://User")));
User user2 = (User) objectInputStream.readObject();
System.out.println(user2);
} finally {
objectOutputStream.close();
objectInputStream.close();
}
}
打印结果:
可以看到,id字段被transient修饰的,所以反序列化后的值为null。
4.关于serialVersionUID
- serialVersionUID是用来反序列化时验证对象是否一致的
现在我们将User对象中的serialVersionUID改为2,然后直接反序列化之前的文件。
private static final long serialVersionUID = 2L;
public static void main(String[] args) throws Exception {
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(new FileInputStream(new File("D://User")));
User user2 = (User) objectInputStream.readObject();
System.out.println(user2);
} finally {
objectInputStream.close();
}
}
Exception in thread "main" java.io.InvalidClassException: com.example.demo.srializable.User; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:616)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1829)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1986)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at com.example.demo.srializable.Test.main(Test.java:16)
可以看到,反序列化时直接报错了,提示serialVersionUID不一致。
本文地址:https://blog.csdn.net/qq_34857603/article/details/107676687
上一篇: 并发容器之ConcurrentLinkedQueue
下一篇: 全网最通俗易懂的【短链接】入门