默认情况下,对象的所有成员变量都将被持久化.在某些情况下,如果你想避免持久化对象的一些成员变量,你可以使用transient关键字来标记他们,transient也是java中的保留字.
java有个特点就是序列化,简单地来说就是可以将这个类存储在物理空间(当然还是以文件的形式存在),那么当你从本地还原这个文件时,你可以将它转换为它本身.这可以极大地方便程序中操作.同时,因为涉及到安全问题,所以并不希望把类里面所有的属性都能存储(因为那样,别人可以通过序列化知道类里面的内容),那么我们就可以用上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
}
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
}
}
}