1 @Test
2 public void testSerializable() throws IOException, ClassNotFoundException {
3 Son son = new Son();
4 son.changeFieldValue();
5 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
6 ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
7 objectOutputStream.writeObject(son);
8 Son.staticField = 3;
9 ObjectInputStream objectInputStream = new ObjectInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
10 son = (Son) objectInputStream.readObject();
11 /**
12 * 输出:
13 * parent
14 * son
15 * parent
16 * Son{staticField=3, s=2, transientField=0, p=1}
17 */
18 System.out.println(son);
19 }
20 private static class Son extends Parent implements Serializable{
21 //正常序列化
22 private int s = 1;
23 //类字段不会参与序列化
24 private static int staticField = 1;
25 //transient字段不会参与序列化
26 private transient int transientField = 1;
27 //由于子类实现了Serializable,故会序列化子类字段,反序列化时不会使用声明的构造器初始化,
28 // 而是使用jvm反射特性直接实例化一个空对象,然后进行赋值,故子类的构造器可以不存在公开、无参构造器。
29 private Son() {
30 System.out.println("son");
31 }
32 private void changeFieldValue() {
33 this.s = 2;
34 Son.staticField = 2;
35 this.transientField = 2;
36 this.p = 2;
37 }
38
39 @Override
40 public String toString() {
41 return "Son{" +
42 "staticField=" + staticField +
43 ", s=" + s +
44 ", transientField=" + transientField +
45 ", p=" + p +
46 '}';
47 }
48 }
49 private static class Parent{
50 //没有实现Serializable的类,字段不会参与序列化
51 protected int p = 1;
52 //由于Parent没有实现Serializable,所以这里的字段不会序列化,
53 //当反序列化子类时,由于没有序列化父类,故需要调用父类的构造器来初始化父类,
54 //父类必须有一个公开、无参的构造函数。
55 public Parent() {
56 System.out.println("parent");
57 }
58 }