Transient关键字的使用
?一個(gè)對(duì)象只要實(shí)現(xiàn)了Serilizable接口,這個(gè)對(duì)象就可以被序列化,然而在實(shí)際開發(fā)過程中有些屬性需要序列化,而其他屬性不需要被序列化,這時(shí)對(duì)應(yīng)的變量就可以加上 transient關(guān)鍵字。
示例:
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable;public class TransientTest {public static void main(String[] args) {User user = new User();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 = new ObjectOutputStream(new FileOutputStream("C:/user.txt"));os.writeObject(user); // 將User對(duì)象寫進(jìn)文件os.flush();os.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}try {ObjectInputStream is = new ObjectInputStream(new FileInputStream("C:/user.txt"));user = (User) is.readObject(); // 從流中讀取User的數(shù)據(jù)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 implements Serializable {private static final long serialVersionUID = 8294180014912103005L; private String username;private transient String passwd;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPasswd() {return passwd;}public void setPasswd(String passwd) {this.passwd = passwd;}}輸出結(jié)果為:
read before Serializable: username: Alexia password: 123456read after Serializable: username: Alexia password: null1)一旦變量被transient修飾,變量將不再是對(duì)象持久化的一部分,該變量?jī)?nèi)容在序列化后無法獲得訪問。
2)transient關(guān)鍵字只能修飾變量,而不能修飾方法和類。注意,本地變量是不能被transient關(guān)鍵字修飾的。變量如果是用戶自定義類變量,則該類需要實(shí)現(xiàn)Serializable接口。
3)被transient關(guān)鍵字修飾的變量不再能被序列化,一個(gè)靜態(tài)變量不管是否被transient修飾,均不能被序列化。
第三點(diǎn)可能有些人很迷惑,因?yàn)榘l(fā)現(xiàn)在User類中的username字段前加上static關(guān)鍵字后,程序運(yùn)行結(jié)果依然不變,即static類型的username也讀出來為“Alexia”了,這不與第三點(diǎn)說的矛盾嗎?實(shí)際上是這樣的:第三點(diǎn)確實(shí)沒錯(cuò)(一個(gè)靜態(tài)變量不管是否被transient修飾,均不能被序列化),反序列化后類中static型變量username的值為當(dāng)前JVM中對(duì)應(yīng)static變量的值,這個(gè)值是JVM中的不是反序列化得出的
參考自:http://www.cnblogs.com/lanxuezaipiao/p/3369962.html
轉(zhuǎn)載于:https://www.cnblogs.com/upcwanghaibo/p/6544660.html
總結(jié)
以上是生活随笔為你收集整理的Transient关键字的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: go map并发写错误问题
- 下一篇: Software Testing Hom