java transient 解析

  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. }  


结果:null密码 

一个对象实现Serializable接口 表示进行序列化(这样在读写文件的时候 通过反序列化可以映射成对象) 也就是写进存储介质  如果该对象某个字段加了transient 表示该属性不需要序列化 也就是不写进存储介质 这样在读写的时候反序列化不了 就为null

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值