Java中的transient关键字

来源:互联网 发布:紫鸟数据魔方收费吗 编辑:程序博客网 时间:2024/05/29 08:57
transient说明一个属性是临时的,不会被序列化。 
下面是一个Demo,name声明为 transient,不被序列化 

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密码  
原创粉丝点击