transient关键字

java中有个transient的关键,该关键字和序列化有关。它的作用是阻止序列化,但要结合实现序列化的方法。
根据java语言规定,被transient修饰的属性将不会被序列化,即通过反序列化的时候取不到有transient修饰字段的值。这种方式是基于实现Serializable 接口的方法。但是在实现Externalizable 接口方式中,不管该属性是否被transient修饰,序列化和反序列化都不取决于它。因为在这个接口中有个void writeExternal(ObjectOutput out) throws IOException 方法,该方法要被重写,通过这个入参,调用它的writeObject(Object obj) 方法把要被序列化的 属性 写进去。反序列化操作和这个相反。
Serializable 接口源码,它里面是空的

public interface Serializable {
}

Externalizable 接口源码,它继承了Serializable 接口

public interface Externalizable extends java.io.Serializable {

void writeExternal(ObjectOutput out) throws IOException;

 void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}

示例:在UserBean中对groupNum不序列化,两种实现方式
实现 Serializable 接口自动完成序列化

public class UserBean implements Serializable {
      protected  String name;
      protected  String nickName;
      protected  String code;
      protected transient  String groupNum;//不会被序列化
     //省略其他代码

}

实现 Externalizable 接口手动完成序列化。
不管是否有transient 修改,只有在writeExternal(ObjectOutput out) 方法中中指定的属性才可以被序列化。

public class UserBean implements Externalizable {
      protected  String name;
      protected  String nickName;
      protected  String code;
      protected transient  String groupNum;//会被序列化

      public void writeExternal(ObjectOutput out) throws IOException{
          out.witeObject(groupNum);
      }

      public void writeExternal(ObjectOutput out) throws IOException{
          groupNum= (String) in.readObject();
      }
     //省略其他代码

}

总结:

  1. transient 关键字是在操作序列化 实现Serializable 接口方式中使用,用来规定属性不会被序列的;
  2. transient 关键字只能左右在类成员属性上,不能用来修饰类、方法或者接口;
  3. 本地属性(方法中声明的变量)上也不能使用transient 修饰,在本地属性上使用transient修饰会报编辑错误Illegal modifier for parameter 参数名称; only final is permitted;
  4. 是否需要序列化取决于业务。
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值