1.在读java的源码时,遇到transient关键字声明变量。例如:
// Generics and annotations support
private transient String signature;
// generic info repository; lazily initialized
private transient FieldRepository genericInfo;
在上面的代码中,不明白 signature和genericInfo声明有什么作用,而且用到了transient关键字修饰。
transient单词意思为瞬态,临时的意思。
对象序列化后读取对象时,瞬态属性不会被读取。
Fields declared as transient or static are ignored by the deserialization process.
对象实现序列化接口后反序列化时,不会创建新的对象,否则会创建。
示例代码:
package my.transientExceple.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;
//测试transient关键字有什么作用
public class LoggingInfo implements 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 "logging info:\n"+"userId:"+uid+",\n loggingDate:+"+loggingDate.toString()+
"\n password:"+password;
}
public static void main(String args[]){
LoggingInfo logInfo = new LoggingInfo("MIKE", "xxxx");
//System.out.println(logInfo.toString());
try {
ObjectOutputStream o = new ObjectOutputStream(
new FileOutputStream("logInfo.out"));
o.writeObject(logInfo);
o.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/* File file=new File("logInfo.out");
System.out.println(file.getAbsoluteFile());
F:\workspace\MyMvc\logInfo.out
*/
try
{
@SuppressWarnings("resource")
ObjectInputStream in =new ObjectInputStream(
new FileInputStream("logInfo.out"));
LoggingInfo logInfo1 = (LoggingInfo)in.readObject();
System.out.println(logInfo1.toString());
}
catch(Exception e) {//deal with exception}
}
}
}