transient關鍵字,javatransient關鍵字

來源:互聯網
上載者:User

transient關鍵字,javatransient關鍵字

transient關鍵字的英文意思是:瞬態,由此可見是瞬間的,不可固定的。

會不會與對象的狀態等等有關係呢? 網上找了一下資料是跟對象的序列化有關。

 

  • transient的作用  

  一個對象只要實現了Serilizable介面,這個對象就可以被序列化,java的這種序列化模式為開發人員提供了很多便利,我們可以不必關係具體序列化的過程,只要這個類實現了Serilizable介面,這個類的所有屬性和方法都會自動序列化。

  在實際開發過程中,我們常常會遇到這樣的問題,這個類的有些屬性需要序列化,而其他屬性不需要被序列化,打個比方,如果一個使用者有一些敏感資訊(如密碼,銀行卡號等),為了安全起見,不希望在網路操作(主要涉及到序列化操作,本地序列化緩衝也適用)中被傳輸,這些資訊對應的變數就可以加上transient關鍵字。換句話說,這個欄位的生命週期僅存於調用者的記憶體中而不會寫到磁碟裡持久化。

  總之,java 的transient關鍵字為我們提供了便利,你只需要實現Serilizable介面,將不需要序列化的屬性前添加關鍵字transient,序列化對象的時候,這個屬性就不會序列化到指定的目的地中。

  如下例子:

 1 public class TransientTest { 2      3     public static void main(String[] args) { 4          5         User user = new User(); 6         user.setUsername("lucy"); 7         user.setPasswd("123456"); 8          9         System.out.println("read before Serializable: ");10         System.out.println("username: " + user.getUsername());11         System.err.println("password: " + user.getPasswd());12         13         try {14             ObjectOutputStream os = new ObjectOutputStream(15                     new FileOutputStream("C:/user.txt"));16             os.writeObject(user); // 將User對象寫進檔案17             os.flush();18             os.close();19         } catch (FileNotFoundException e) {20             e.printStackTrace();21         } catch (IOException e) {22             e.printStackTrace();23         }24         try {25             ObjectInputStream is = new ObjectInputStream(new FileInputStream(26                     "C:/user.txt"));27             user = (User) is.readObject(); // 從流中讀取User的資料28             is.close();29             30             System.out.println("\nread after Serializable: ");31             System.out.println("username: " + user.getUsername());32             System.err.println("password: " + user.getPasswd());33             34         } catch (FileNotFoundException e) {35             e.printStackTrace();36         } catch (IOException e) {37             e.printStackTrace();38         } catch (ClassNotFoundException e) {39             e.printStackTrace();40         }41     }42 }43 44 class User implements Serializable {45     private static final long serialVersionUID = 8294180014912103005L;  46     47     private String username;48     private transient String passwd;49     50     public String getUsername() {51         return username;52     }53     54     public void setUsername(String username) {55         this.username = username;56     }57     58     public String getPasswd() {59         return passwd;60     }61     62     public void setPasswd(String passwd) {63         this.passwd = passwd;64     }65 66 }

  輸出結果:

1 read before Serializable: 2 username: lucy3 password: 1234564 5 read after Serializable: 6 username: lucy7 password: null
  • transient注意點

  1、一旦變數被transient修飾,變數將不再是對象持久化的一部分,該變數內容在序列化後無法獲得訪問。

  2、transient關鍵字只能修飾變數,而不能修飾方法和類。注意,本地變數是不能被transient關鍵字修飾的。變數如果是使用者自訂類變數,則該類需要實現Serializable介面。

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

  如下代碼:

 1 public class TransientTest { 2      3     public static void main(String[] args) { 4          5         User user = new User(); 6         user.setUsername("lucy"); 7         user.setPasswd("123456"); 8          9         System.out.println("read before Serializable: ");10         System.out.println("username: " + user.getUsername());11         System.err.println("password: " + user.getPasswd());12         13         try {14             ObjectOutputStream os = new ObjectOutputStream(15                     new FileOutputStream("C:/user.txt"));16             os.writeObject(user); // 將User對象寫進檔案17             os.flush();18             os.close();19         } catch (FileNotFoundException e) {20             e.printStackTrace();21         } catch (IOException e) {22             e.printStackTrace();23         }24         try {25             // 在還原序列化之前改變username的值26             User.username = "jack";27             28             ObjectInputStream is = new ObjectInputStream(new FileInputStream(29                     "C:/user.txt"));30             user = (User) is.readObject(); // 從流中讀取User的資料31             is.close();32             33             System.out.println("\nread after Serializable: ");34             System.out.println("username: " + user.getUsername());35             System.err.println("password: " + user.getPasswd());36             37         } catch (FileNotFoundException e) {38             e.printStackTrace();39         } catch (IOException e) {40             e.printStackTrace();41         } catch (ClassNotFoundException e) {42             e.printStackTrace();43         }44     }45 }46 47 class User implements Serializable {48     private static final long serialVersionUID = 8294180014912103005L;  49     50     public static String username;51     private transient String passwd;52     53     public String getUsername() {54         return username;55     }56     57     public void setUsername(String username) {58         this.username = username;59     }60     61     public String getPasswd() {62         return passwd;63     }64     65     public void setPasswd(String passwd) {66         this.passwd = passwd;67     }68 69 }

  輸出結果:

read before Serializable: username: lucypassword: 123456read after Serializable: username: jackpassword: null

  這說明還原序列化後類中static型變數username的值為當前JVM中對應static變數的值,而不是通過還原序列化得到的值。

  • transient細節
 1 public class ExternalizableTest implements Externalizable { 2  3     private transient String content = "是的,我將會被序列化,不管我是否被transient關鍵字修飾"; 4  5     @Override 6     public void writeExternal(ObjectOutput out) throws IOException { 7         out.writeObject(content); 8     } 9 10     @Override11     public void readExternal(ObjectInput in) throws IOException,12             ClassNotFoundException {13         content = (String) in.readObject();14     }15 16     public static void main(String[] args) throws Exception {17         18         ExternalizableTest et = new ExternalizableTest();19         ObjectOutput out = new ObjectOutputStream(new FileOutputStream(20                 new File("test")));21         out.writeObject(et);22 23         ObjectInput in = new ObjectInputStream(new FileInputStream(new File(24                 "test")));25         et = (ExternalizableTest) in.readObject();26         System.out.println(et.content);27 28         out.close();29         in.close();30     }31 }

  輸出結果:

是的,我將會被序列化,不管我是否被transient關鍵字修飾

  在Java中,對象的序列化可以通過實現兩種介面來實現,若實現的是Serializable介面,則所有的序列化將會自動進行,若實現的是Externalizable介面,則沒有任何東西可以自動序列化,需要在writeExternal方法中進行手工指定所要序列化的變數,這與是否被transient修飾無關。因此第二個例子輸出的是變數content初始化的內容,而不是null。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.