首页 > 其他 > 详细

Transient关键字的作用

时间:2014-07-25 16:42:31      阅读:534      评论:0      收藏:0      [点我收藏+]

在对象序列化的时候,有些变量不需要序列化,比如密码等,可以使用transient关键字来解决这个问题,transient修饰的变量不会被序列化。

例子:

 1 import java.io.*;
 2 import java.util.Date;
 3  
4
5 /** 6 * Created by leiqiang on 2014/7/25. 7 */ 8 public class TransientTest implements Serializable{ 9 private Date date = new Date(); 10 private String username; 11 private transient String password; 12 13 public TransientTest(String username,String password){ 14 this.username=username; 15 this.password=password; 16 } 17 18 @Override 19 public String toString() { 20 return new Date()+" username "+username+" : password "+password; 21 } 22 23 public static void main(String[] args) throws Exception{ 24 TransientTest transientTest = new TransientTest("lei","1234"); 25 System.out.println(transientTest); 26 FileOutputStream fileOutputStream = new FileOutputStream("d:/Cache/TransientTest.txt"); 27 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); 28 objectOutputStream.writeObject(transientTest); 29 objectOutputStream.close(); 30 Thread.sleep(2000); 31 FileInputStream fileInputStream = new FileInputStream("d:/Cache/TransientTest.txt"); 32 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); 33 transientTest = (TransientTest)objectInputStream.readObject(); 34 System.out.println(transientTest); 35 } 36 }

运行结果:

1 Fri Jul 25 13:56:13 CST 2014 username lei : password 1234
2 Fri Jul 25 13:56:15 CST 2014 username lei : password null

Transient关键字的作用,布布扣,bubuko.com

Transient关键字的作用

原文:http://www.cnblogs.com/leistrong/p/3867885.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!