您的位置:首页 > 其它

transient关键字

2016-12-19 16:49 197 查看
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();
}
//省略其他代码

}


总结:

transient 关键字是在操作序列化 实现Serializable 接口方式中使用,用来规定属性不会被序列的;

transient 关键字只能左右在类成员属性上,不能用来修饰类、方法或者接口;

本地属性(方法中声明的变量)上也不能使用transient 修饰,在本地属性上使用transient修饰会报编辑错误Illegal modifier for parameter 参数名称; only final is permitted;

是否需要序列化取决于业务。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  transient