【发布时间】:2015-07-01 10:47:23
【问题描述】:
请澄清我为什么在反序列化后获得公司价值。我知道“静态是隐含的瞬态,所以我们不需要这样声明它们。”
class Employee implements Serializable {
String name;
static String company = "My Company";
public Employee(String name) {
this.name = name;
}
}
public class Test8 {
public static void main(String[] args) throws Exception {
Employee e = new Employee("John");
serializeObject(e);// assume serialize works fine
Employee e1 = deserializeObject(); // assume deserialize works fine
System.out.println(e1.name + " " + e1.company);
}
public static void serializeObject(Employee e) throws IOException {
FileOutputStream fos = new FileOutputStream("Test8.cert");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.flush();
oos.close();
}
public static Employee deserializeObject() throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream("Test8.cert");
ObjectInputStream oos = new ObjectInputStream(fis);
return (Employee) oos.readObject();
}
}
【问题讨论】:
-
什么是
serializeObject()和deserializeObject()? -
添加了这两种方法。
-
因为你在同一个JVM中,所以类没有重新初始化。
-
如果它们是隐式瞬态,那么它们不会被序列化。
标签: java