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密码  


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