天天看點

transient java_java Transient關鍵字的使用

@Transient表示該屬性字段的生命周期僅存于調用者的記憶體中而不會寫到磁盤裡持久化

如果一個屬性并非資料庫表的字段映射,就務必将其标示為@Transient,否則,ORM架構預設其注解為@Basic

示例:

//根據birth計算出age屬性

@Transientpublic intgetAge() {return getYear(new CurrentYear()) -getYear(birth);

}

一個對象隻要實作了Serilizable接口,這個對象就可以被序列化,然而在實際開發過程中有些屬性需要序列化,而其他屬性不需要被序列化,這時對應的變量就可以加上 transient關鍵字。

示例:

importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.ObjectInputStream;importjava.io.ObjectOutputStream;importjava.io.Serializable;

public classTransientTest {public static voidmain(String[] args) {

User user= newUser();

user.setUsername("Alexia");

user.setPasswd("123456");

System.out.println("read before Serializable: ");

System.out.println("username: " +user.getUsername());

System.err.println("password: " +user.getPasswd());try{

ObjectOutputStream os= newObjectOutputStream(new FileOutputStream("C:/user.txt"));

os.writeObject(user);//将User對象寫進檔案

os.flush();

os.close();

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}try{

ObjectInputStream is= new ObjectInputStream(newFileInputStream("C:/user.txt"));

user= (User) is.readObject(); //從流中讀取User的資料

is.close();

System.out.println("\nread after Serializable: ");

System.out.println("username: " +user.getUsername());

System.err.println("password: " +user.getPasswd());

}catch(FileNotFoundException e) {

e.printStackTrace();

}catch(IOException e) {

e.printStackTrace();

}catch(ClassNotFoundException e) {

e.printStackTrace();

}

}

}class User implementsSerializable {private static final long serialVersionUID = 8294180014912103005L;privateString username;private transientString passwd;publicString getUsername() {returnusername;

}public voidsetUsername(String username) {this.username =username;

}publicString getPasswd() {returnpasswd;

}public voidsetPasswd(String passwd) {this.passwd =passwd;

}

}

輸出結果為:

read before Serializable:

username: Alexia

password:123456read after Serializable:

username: Alexia

password:null

1)一旦變量被transient修飾,變量将不再是對象持久化的一部分,該變量内容在序列化後無法獲得通路。

2)transient關鍵字隻能修飾變量,而不能修飾方法和類。注意,本地變量是不能被transient關鍵字修飾的。變量如果是使用者自定義類變量,則該類需要實作Serializable接口。

3)被transient關鍵字修飾的變量不再能被序列化,一個靜态變量不管是否被transient修飾,均不能被序列化。

第三點可能有些人很迷惑,因為發現在User類中的username字段前加上static關鍵字後,程式運作結果依然不變,即static類型的username也讀出來為“Alexia”了,這不與第三點說的沖突嗎?實際上是這樣的:第三點确實沒錯(一個靜态變量不管是否被transient修飾,均不能被序列化),反序列化後類中static型變量username的值為目前JVM中對應static變量的值,這個值是JVM中的不是反序列化得出的

參考自:http://www.cnblogs.com/lanxuezaipiao/p/3369962.html