请清楚我的理解为什么我在反序列化后获得了公司的价值。我知道“静态是隐式瞬态的,所以我们不需要声明它们。”
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();
}
}
答案 0 :(得分:1)
静态字段company
的值是在您第一次使用Employee
类时设置的。在你的情况下,它将符合:
Employee e = new Employee("John");
这个值没有改变,因为它没有被序列化和反序列化所以它保持不变,这意味着
System.out.println(e1.name + " " + e1.company);
打印John My Company
。
但即使你删除行
Employee e = new Employee("John");
serializeObject(e);
从您的代码,仅调用
public static void main(String[] args) throws Exception {
Employee e1 = deserializeObject(); // assume deserialize works fine
System.out.println(e1.name + " " + e1.company);
}
Employee
类仍将在deserializeObject
内加载(通过oos.readObject()
方法),因此其静态字段也将正确初始化为其默认值。