结论
1.不管是否设置 serialVersionUID ,要想进行序列化与反序列化,就必须保证类的全称一致。
2.如果序列化类和反序列化的类都不设置 serialVersionUID ,那么要想正常进行序列化和反序列化,则需要保持两个类的结构一致。
3.如果两个类的结构不同,那么 serialVersionUID 设置相同时,也可以进行序列化和反序列化
证明
场景一:不使用 serialVersionUID ,类名一致,结构不一致,失败
①.序列化类
package com.test;
import lombok.Data;
import java.io.Serializable;
@Data
public class Person implements Serializable {
private String name;
private int age;
}
②.序列化代码
package com.test;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\yinguoyu\\Desktop\\object.txt"))){
Person person = new Person();
person.setName("ygy");
oos.writeObject(person);
} catch (Exception e){
e.printStackTrace();
}
}
}
③.反序列化类
package com.test;
import lombok.Data;
import java.io.Serializable;
@Data
public class Person implements Serializable {
private String name;
}
④.反序列化代码
package com.test;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class Test {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\yinguoyu\\Desktop\\object.txt"))){
Person person = (Person)ois.readObject();
System.out.println(person);
} catch (Exception e){
e.printStackTrace();
}
}
}
⑤.测试结果:报错
场景二:使用 serialVersionUID ,类名一致,结构不一致,成功
修改:把序列化类和反序列化类都加上 serialVersionUID 即可
①.序列化类
package com.test;
import lombok.Data;
import java.io.Serializable;
@Data
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
}
②.反序列化类
package com.test;
import lombok.Data;
import java.io.Serializable;
@Data
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
}