Person.java
package a.b.c; public class Person implements java.io.Serializable{ // private static final long serialVersionUID = 2481632967198330813L; String field1; String field2; String field3; public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } }
Student.java Student继承自Person,但为了清晰表示,按Person一模一样又覆盖了一遍
package a.b.c; public class Student extends Person implements java.io.Serializable { // private static final long serialVersionUID = 2481632967198330813L; String field1; String field2; String field3; public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } }
SerializableWriter.java
package a.b.c; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; public class SerializableWriter { public static void main(String[] args) throws Exception{ write(); } public static void write() throws Exception{ Student stu= new Student(); stu.setField1("aaa111"); stu.setField2("bbb222"); ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("C:/Users/King/Desktop/jx.txt")); objectOutputStream.writeObject(stu); objectOutputStream.flush(); objectOutputStream.close(); } }
SerializableReader.java
package a.b.c; import java.io.FileInputStream; import java.io.ObjectInputStream; public class SerializableReader { public static void main(String[] args) throws Exception{ read(); } public static void read() throws Exception{ ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("C:/Users/King/Desktop/jx.txt")); Object obj=objectInputStream.readObject(); Person person=(Person)obj; System.out.println(person.getField1()); System.out.println(person.getField2()); objectInputStream.close(); } }
打印结果
aaa111 bbb222
总结
- 只要版本号一致,且Student就算删掉field3的属性和方法,仍旧可以把序列化后的Student反序列化成Student.
- 只要版本号一致,且Student 继承自父类 Person,那么就可以把序列化后的Student反序列化成Person.
时间: 2024-09-28 20:15:00