首先先说一下这个修饰符作用:我们把对象序列化的时候,不希望对类中其中某个属性也进行序列化,那么就可以用这个transient进行修饰了。比如将对象存在磁盘中,就不会将用transient这个修饰符的属性变量也写到磁盘中,比如把变量通过网络传送,那么就不会将这个属性传输过去。这样是不是安全了许多
下面通过一个实例来完成探索的最后一步,为了提高英语水平,之前就下决定用不再用中文注释,中国式的英语,老外绝对看不懂
package com.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class TransientTest implements Serializable {
private static final long serialVersionUID = 1L;
private String path;
private String username;
private transient String password;
public TransientTest(String username,String password){
this.username = username;
this.password = password;
}
public String toString(){
return username +" " + password;
}
/** write the Object to the special File path */
public void writeToFile() throws FileNotFoundException, IOException{
path = System.getProperty("user.dir")+"\\"+"Object.write";
System.out.println("before write Object ,let's display the variable modifier by transient"+password);
//form here ,we can know the constructor initialized transient.
//but when serializable object,will ignore the variable modifier by transient
//in other words that the variable has not written into the File
System.out.println(path);
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File(path)));
oos.writeObject(this);
oos.close();
}
/** get the Object from special File path**/
public void readFromFile() throws FileNotFoundException, IOException, ClassNotFoundException{
//due to read the Object from the diskette,in fact that it's not executing constructor
//rather than load the the persistence status of the object and assign it to other target
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path));
TransientTest tt = (TransientTest) ois.readObject();
System.out.println(tt.toString());
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
//now let's test the difference between the variable modifier by transient and others
TransientTest transientTest = new TransientTest("正常变量","经过修饰的变量");
transientTest.writeToFile();
transientTest.readFromFile();
}
}
结果如下
before write Object ,let's display the variable modifier by transient经过修饰的变量
C:\Users\1\Workspaces\MyEclipse 8.6\Struts2WebTest\Object.write
正常变量 null
这里null就可以验证上边的猜想
引用别人的话:
当从磁盘中读出某个类的实例时,实际上并不会执行这个类的构造函数, 而是载入了一个该类对象的持久化状态,并将这个状态赋值给该类的另一个对象。