transient這個關鍵字不怎麼常用在web應用開發中。但也是要知道有這麼一個東西的。主要的用途在序列化中,下面貼上一段來自網上的例子就明白了
import java.io.*;
import java.util.*;
class logon implements serializable {
private static final long serialversionuid = -732613846174452100l;
private date date = new date();
private string username;
private transient string password;
logon(string name, string pwd) {
username = name;
password = pwd;
}
public string tostring() {
string pwd = (password == null) ? "(n/a)" : password;
return "logon info: \n " + "username: " + username + "\n date: "
+ date.tostring() + "\n password: " + pwd;
public static void main(string[] args) {
logon a = new logon("hulk", "mylittlepony");
system.out.println("logon a = " + a);
try {
objectoutputstream o = new objectoutputstream(new fileoutputstream(
"logon.out"));
o.writeobject(a);
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(
system.out.println();
system.out.println("recovering object at " + new date());
a = (logon) in.readobject();
system.out.println("logon a = " + a);
} catch (exception e) {
e.printstacktrace();
}
} // /:~