Java中transientkeyword的应用
今天跟JDK源代码的时候发现transient ,感觉从来没见过,于是用google查了一下.
Java语言的keyword,用来表示一个域不是该对象串行化的一部分。当一个对象被串行化的时候,transient型变量的值不包含在串行化的表示中,然而非transient型的变量是被包含进去的。
以下我们查创建一个LoginFile的类:
public class LoginFile implements Serializable{ private static final long serialVersionUID = 1L; private String name = null; private transient String pwd = null; public LoginFile() { name = "shirdey"; pwd = "654321"; } public String toString(){ return "ClassName:LoginFile" +"\nname = "+name +"\npwd = "+pwd; } }
然后初始化LoginFile对象,将该对象写到硬盘上:
LoginFile loginFile = new LoginFile(); System.out.println(loginFile.toString()); try { ObjectOutputStream outputStream = new ObjectOutputStream (new FileOutputStream("login.out")); outputStream.writeObject(loginFile); outputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }
此时打开login.out文件看不到pwd字段没,然后我们通过读取login.out測试一下:
try { ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("login.out")); LoginFile loginFile = (LoginFile) inputStream.readObject(); System.out.println(loginFile.toString()); } catch (Exception e) { }
output:
ClassName:LoginFile name = shirdey pwd = null
非常明显,被transient改动的pwd字段并没有被保存在硬盘
当串行化某个对象时,如果该对象的某个变量是transient。那么这个变量不会被串行化进去。
也就是说,如果某个类的成员变量是transient,那么当通过ObjectOutputStream把这个类的某个实例
保存到磁盘上时,实际上transient变量的值是不会保存的。
由于当从磁盘中读出这个对象的时候,对象的该变量会没有被赋值。
另外这篇文章还提到,当从磁盘中读出某个类的实例时,实际上并不会运行这个类的构造函数,而是读取这个类的实例的状态。而且把这个状态付给这个类的对象。
这点我曾经似乎不知道。
參考文献:http://www.devx.com/tips/Tip/13726