58,454
社区成员
发帖
与我相关
我的任务
分享
import java.io.*;
import java.util.*;
public class Test implements Serializable {
private String a;
private transient String b;
private static String c;
public Test(String a, String b, String c) {
this.a = "Not transient: " + a;
this.b = "Transient: " + b;
this.c = "static: " + c;
}
/* public void setC(String c1) {
c = c1;
}*/
public String toString() {
return a + "\n" + b + "\n" + c;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Test t1 = new Test("Test1", "Test2", "Test3");
System.out.println("Before:\n" + t1);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.txt"));
out.writeObject(t1);
out.close();
//t1.setC("ccc");
ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.txt"));
Test t2 = (Test)in.readObject();
in.close();
System.out.println("After:\n" + t2);
}
}
你可以试下上面的代码,输出结果是:
Before:
Not transient: Test1
Transient: Test2
static: Test3
After:
Not transient: Test1
null
static: Test3
但是如果去掉注释,输出结果是:
Before:
Not transient: Test1
Transient: Test2
static: Test3
After:
Not transient: Test1
null
ccc
静态变量在序列化后才被改为ccc,但是反序列化后读出来就是ccc了,说明静态变量不会被序列化,因为它是与类相关而不是与对象相关的,但是反序列的时候重构对象,静态变量最终为什么值就会被注入什么值。
可参考博文:http://blog.csdn.net/u010729348/article/details/21046737