我一直在阅读关于静态字段不会被序列化的说法,但进行测试后发现这并不正确。静态修饰符甚至可以覆盖瞬态修饰符,并使字段可被序列化。我在书中找到了一个例子,展示了静态瞬态字段是如何被序列化的。
import java.io.*;
class USPresident implements Serializable {
private static final long serialVersionUID = 1L;
@Override
public String toString() {
return "US President [name=" + name
+ ", period=" + period + ", term=" + term + "]";
}
public USPresident(String name, String period, String term) {
this.name = name;
this.period = period;
this.term = term;
}
private String name;
private String period;
private static transient String term;
}
class TransientSerialization {
public static void main(String[] args) {
USPresident usPresident = new USPresident("Barack Obama", "2009 to --", "56th term");
System.out.println(usPresident);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("USPresident.data"))) {
oos.writeObject(usPresident);
} catch (IOException ioe) {
// ignore
}
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("USPresident.data"))) {
Object obj = ois.readObject();
if (obj != null && obj instanceof USPresident) {
USPresident presidentOfUS = (USPresident) obj;
System.out.println(presidentOfUS);
}
} catch (IOException ioe) {
// ignore
} catch (ClassNotFoundException e) {
// ignore
}
}
}
静态字段不会被序列化的普遍观念是错误的吗?这只是一个建议吗?为什么transient修饰符对静态字段不起作用?
注:我知道在构造函数中初始化静态字段是一种奇怪的代码,但编译器允许我这样做,只是为了理解静态字段的序列化。