首页 > 代码库 > Transient关键字的作用

Transient关键字的作用

在对象序列化的时候,有些变量不需要序列化,比如密码等,可以使用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 @Override19 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 12342 Fri Jul 25 13:56:15 CST 2014 username lei : password null