Java 实体类中的 serialVersionUID 作用解释
实验一: 实体 User 中没有 serialVersionUID 字段的时候
1 @Data 2 public class User implements Serializable {3 4 5 private Integer id; 6 7 private String name; 8 9 }
test 代码:
1 @Test 2 void testSerilze() throws Exception {
// 序列化 user 对象保存到文件中 3 User user = new User(); 4 user.setName("wahahha"); 5 FileOutputStream outputStream = new FileOutputStream("user"); 6 ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); 7 objectOutputStream.writeObject(user); 8 objectOutputStream.close(); 9 10 }
11 @Test 12 void testRead() throws Exception{
//从文件中反序列化 user 对象 13 FileInputStream inputStream = new FileInputStream("user"); 14 ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); 15 User user = (User)objectInputStream.readObject(); 16 System.out.println(user); 17 }
输入结果正常: User(id=null, name=wahahha, age=null)
public class User implements Serializable { private Integer id; private String name; // 添加字段 age private Integer age; }
执行 test:
@Test void testRead() throws Exception{ FileInputStream inputStream = new FileInputStream("user"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); User user = (User)objectInputStream.readObject(); System.out.println(user); }
抛出异常:
java.io.InvalidClassException: com.ym.mybatisplus.pojo.User; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = -8191989038804560538
结果证明: 如果没有 serialVersionUID 字段, 那么实体类如果改变,那么再反序列化的时候,就会导致失败,抛出异常
实验二: 实体 User 中添加 serialVersionUID 字段
@Data public class User implements Serializable { private static final long serialVersionUID=1L; private Integer id; private String name; }
执行序列化:
@Test void testSerilze() throws Exception { User user = new User(); user.setName("wahahha"); FileOutputStream outputStream = new FileOutputStream("user"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(user); objectOutputStream.close(); }
然后修改 User, 添加字段 age:
@Data public class User implements Serializable { private static final long serialVersionUID=1L; private Integer id; private String name; private Integer age; }
然后执行反序列化:
@Test void testRead() throws Exception{ FileInputStream inputStream = new FileInputStream("user"); ObjectInputStream objectInputStream = new ObjectInputStream(inputStream); User user = (User)objectInputStream.readObject(); System.out.println(user); }
正常输出反序列化结果:
User(id=null, name=wahahha, age=null)
结果证明: serialVersionUID 字段可以用来保证对象的一致性,在序列化和反序列化的时候,可以保持兼容性,可以正确反序列化成功。