java有个特点就是序列化,简单地来说就是可以将这个对象存储在物理空间(当然还是以文件的形式存在),那么当你从本地还原这个文件时,你可以将它转换为它本身。这可以极大地方便网络上的一些操作,但同时,因为涉及到安全问题,所以并不希望把对象里面所有的东西都能存储(因为那样,别人可以通过序列化知道对象里面的内容),那么我们就可以用上transient这个关键字,它的意思是临时的,即不会随对象一起序列化到本地,所以当还原后,这个关键字定义的变量也就不再存在。
看看下面的例子,一个登陆时,密码与ID,密码最后没打印,就会明白transient 是干什么了。
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;
public class LoggingInfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Date loggingDate = new Date();
private String uid;
private transient String pwd;
LoggingInfo(String user, String password) {
uid = user;
pwd = password;
}
public String toString() {
String password = null;
if (pwd == null) {
password = "NOT SET";
} else {
password = pwd;
}
return "logon info: \n " + "user: " + uid + "\n logging date : "
+ loggingDate.toString() + "\n password: " + password;
}
public static void main(String[] args) {
LoggingInfo logInfo = new LoggingInfo("MIKE", "MECHANICS");
System.out.println(logInfo.toString());
try {
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"logInfo.out"));
o.writeObject(logInfo);
o.close();
} catch (Exception e) {// deal with exception
}
// To read the object back, we can write
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"logInfo.out"));
LoggingInfo logInfo1 = (LoggingInfo) in.readObject();
System.out.println(logInfo1.toString());
} catch (Exception e) {// deal with exception
}
}
}
打印结果:
logon info:
user: MIKE
logging date : Wed Mar 18 02:43:51 GMT 2009
password: MECHANICS
logon info:
user: MIKE
logging date : Wed Mar 18 02:43:51 GMT 2009
password: NOT SET