transient 字段反序列化后是字段类型默认值

transient 字段

  • 一些不必要同步的字段,在集群间不传递,因此设置为transient
  • transient字段就算赋值了,反序列化后,是默认值

一些不必要同步的字段,在集群间不传递,因此设置为transient

因为一些字段没有在要求集群间必须传递,只在各自主机上保持唯一即可.对这样的需求,当然是使用标记transient了.

序列化对象例子

class SpecialSerial implements Serializable {
    private static final long serialVersionUID = -4464442243709562174L;
    transient int y=100;
    static int z = 9;
    public SpecialSerial(){
        System.out.println("set value for y");
        this.y=100;
        System.out.println("y:"+y);
    };
}

transient字段就算赋值了,就算默认构造函数中有值,反序列化后,还是默认值

public class TestClass {
  static public void main(String[] args) {
    SpecialSerial s1 = new SpecialSerial();
    try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myFile"));
        os.writeObject(s1);
        os.close();
        System.out.println("------------------------------------");

        ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));
        SpecialSerial s2 = (SpecialSerial)is.readObject();
        is.close();
        System.out.println("y:"+s2.y + " ;  z:" + s2.z);
    } catch (Exception e) {e.printStackTrace();}
  }
}

想想也是必然,readObject时候,其实transient的值也是有的,但是这时就已经是默认值了.

输出结果

set value for y
y:100
------------------------------------
y:0 ;  z:9

可见,在进行反序列化的时候,并没调用类的构造方法.而是直接根据序列化数据在内存中创建新的对象.

还真没仔细看过关于序列化的文章,看来要详细看下.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值