【发布时间】:2013-12-17 23:07:10
【问题描述】:
我一直在读到静态字段没有序列化,但经过测试,我发现这不是真的。
静态修饰符甚至覆盖瞬态修饰符并使字段可序列化。
我从一本书中写了一个例子,表明静态瞬态字段是序列化的。
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
}
}
}
静态字段不序列化的一般概念是错误的吗?仅仅是推荐吗? 为什么瞬态修饰符对 static 不起作用?
注意:我知道在构造函数中初始化静态字段是一个奇怪的代码,但编译器让我这样做,这只是为了理解静态字段序列化。
【问题讨论】:
-
您的代码并不能证明任何事情:类的所有实例的静态值都是相同的,因此它不会改变是正常的...尝试读取您的文件而不用相同的方式写入之前的节目。
标签: java serialization static