package com.jshow.arithmetic.interview; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; /** * Transient * @author HXQ * */ public class TransientTest implements Serializable { private Date date = new Date(); private String username; private transient String password; TransientTest(String name, String pwd) { username = name; password = pwd; } public String toString() { String pwd = (password == null) ? "(n/a)" : password; return "TransientTest outPut: /n " + "username: " + username + "/n date: " + date.toString() + "/n password: " + pwd; } public static void main(String[] args) { TransientTest a = new TransientTest("Hulk", "myLittlePony"); System.out.println( "TransientTest AAA = " + a); try { ObjectOutputStream o = new ObjectOutputStream( new FileOutputStream("Logon.out")); o.writeObject(a); System.out.println("*****************************"); o.close(); // Delay: int seconds = 5; long t = System.currentTimeMillis() + seconds * 1000; while(System.currentTimeMillis() < t) ; // Now get them back: ObjectInputStream in = new ObjectInputStream(new FileInputStream("Logon.out")); System.out.println( "Recovering object at " + new Date()); a = (TransientTest)in.readObject(); System.out.println( "TransientTest BBBBB = " + a); } catch(Exception e) { e.printStackTrace(); } } }
运行结果如下:看了大家就明白是怎么回事了
TransientTest AAA = TransientTest outPut:
username: Hulk
date: Sun Sep 05 15:16:14 CST 2010
password: myLittlePony
*****************************
Recovering object at Sun Sep 05 15:16:19 CST 2010
TransientTest BBBBB = TransientTest outPut:
username: Hulk
date: Sun Sep 05 15:16:14 CST 2010
password: (n/a)