transient 關鍵詞的作用:
在使用隱式序列化【Serializable】時,被transient 修飾的屬性,無法被序列化,存到文件中。
PS : 在使用隱式序列化【Serializable】時,被static 修飾的屬性也會禁止序列化
場景:
1、類中的屬性 ,可以通過其他屬性計算得出的。例如: 長 、寬、面積,其中面積就可以不用序列化,可節約空間
2、一些敏感的信息,如 密碼之類的信息,
3、根據具體的業務場景使用transient 關鍵詞
注意點 :
1、不是使用了 transient 、static關鍵詞修飾了某個屬性, 就代表這個屬性不可被序列化:
如果是使用顯式序列化【Externalizable】,則關鍵詞【transient、static】失去禁止序列化的作用。
決定是否被數列化取決於writeExternal(ObjectOutput out) 中有沒有將這個屬性寫入到存儲的文件中。
這個接口需要使用2個方法:writeExternal(ObjectOutput out) 和 readExternal(ObjectInput in) :代碼示例如下【僞代碼】:
序列化類:
public class person implements Externalizable{
private String name;
private transient int age;
private String hobby;
writeExternal(ObjectOutput out) {
out.writeObject(this.name);
out.writeObject(this.age);
}
readExternal(ObjectInput in){
this.name = (String) in.readObject();
this.age = (int) in.readObject();
}
}
測試類:
public class Test{
public static void main(String[] args){
setName = "路飛";
setAge = "18";
setHobby = "reading"
System.out.print(person);// name="路飛",age=18;
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\1.txt"));
oos.writeObject(person);
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\1.txt"));
Person p= (Person)ois.readObject();
System.out.print(person);// name="路飛",age=18;
}
}
其中:
1、使用Externalizable,不管這個屬性有沒有被transient 、static 修飾,都可以序列化
2、這2個方法中的屬性順序必須保持一致【順序、數量,一一對應】,
如有遺漏或錯誤請指出。