java序列化 静态变量,静态类变量和序列化/反序列化

From the SCJP 6 study guide - there is a question asking for the output of the following code regarding serialization:

import java.io.*;

public class TestClass {

static public void main(String[] args) {

SpecialSerial s = new SpecialSerial();

try {

ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myFile"));

os.writeObject(s);

os.close();

System.out.print(++s.z + " ");

s = null; // makes no difference whether this is here or not

ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));

SpecialSerial s2 = (SpecialSerial)is.readObject();

is.close();

System.out.println(s2.y + " " + s2.z);

} catch (Exception e) {e.printStackTrace();}

}

}

class SpecialSerial implements Serializable {

transient int y = 7;

static int z = 9;

}

The output of this is: 10 0 10

The reason given for this is that the static variable z is not serialized, which I would not have expected it to be.

The value of the static int variable z is incremented to 10 after the object has been written to file, in the println() statement.

This being the case, why is it not back to either it's original value of 9 when the class is deserialized, or as the class is not being created in the normal way, the class default int value of 0, rather than remaining with it's non-default incremented value of 10 after deserialization? I would have thought the value of it being 10 would be lost, but this is not the case.

Anyone shed some light? I'm stumbling around here in the dark stubbing my toes on this one..

解决方案

Basically, instances are serialized, not classes. Any static fields declared by the class are unaffected by serialization/deserialization of an instance of the class. For z to be reset to 9, the SpecialSerial class would need to be reloaded, which is a different matter.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值