Java中的transient關鍵字

transient  報錯

 英 ['trnznt]  美 ['trnzrnt]  全球發音 跟讀 口語練習

  • adj. 短暫的;路過的

  • n. 瞬變現象;過往旅客;候鳥


java語言的關鍵字,變量修飾符,如果用transient聲明一個實例變量,當對象存儲時,它的值不需要維持。

作用

Java的serialization提供了一種持久化對象實例的機制。當持久化對象時,可能有一個特殊的對象數據成員,我們不想用serialization機制來保存它。爲了在一個特定對象的一個域上關閉serialization,可以在這個域前加上關鍵字transient。當一個對象被序列化的時候,transient型變量的值不包括在序列化的表示中,然而非transient型的變量是被包括進去的。


transient說明一個屬性是臨時的,不會被序列化。 
下面是一個Demo,name聲明爲 transient,不被序列化 。這個在C#裏面是特性[ignore]而不是關鍵字。

Java代碼  收藏代碼

  1. package com.zzs.tet;  

  2.   

  3. import java.io.File;  

  4. import java.io.FileInputStream;  

  5. import java.io.FileNotFoundException;  

  6. import java.io.FileOutputStream;  

  7. import java.io.IOException;  

  8. import java.io.ObjectInput;  

  9. import java.io.ObjectInputStream;  

  10. import java.io.ObjectOutput;  

  11. import java.io.ObjectOutputStream;  

  12. import java.io.Serializable;  

  13.   

  14. public class TransientDemo implements Serializable{  

  15.     /** 

  16.      *  

  17.      */  

  18.     private static final long serialVersionUID = 1L;  

  19.     private  transient String name;  

  20.     private String password;  

  21.       

  22.     public String getName() {  

  23.         return name;  

  24.     }  

  25.   

  26.     public void setName(String name) {  

  27.         this.name = name;  

  28.     }  

  29.   

  30.     public String getPassword() {  

  31.         return password;  

  32.     }  

  33.   

  34.     public void setPassword(String password) {  

  35.         this.password = password;  

  36.     }  

  37.   

  38.     /** 

  39.      * @param args 

  40.      * @throws IOException  

  41.      * @throws FileNotFoundException  

  42.      * @throws ClassNotFoundException  

  43.      */  

  44.     public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {  

  45.         // TODO Auto-generated method stub  

  46.         String path="D:"+File.separator+"object.txt";  

  47.         File file=new File(path);  

  48.         TransientDemo transientDemo=new TransientDemo();  

  49.         transientDemo.setName("姓名");  

  50.         transientDemo.setPassword("密碼");  

  51.         ObjectOutput output=new ObjectOutputStream(new FileOutputStream(file));  

  52.         output.writeObject(transientDemo);  

  53.         ObjectInput input=new ObjectInputStream(new FileInputStream(file));  

  54.         TransientDemo demo=(    TransientDemo )input.readObject();  

  55.         System.out.println(demo.getName()+demo.getPassword());  

  56.     }  

  57.   

  58. }  


輸出結果: 

Java代碼  收藏代碼

  1. null密碼  


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章