【问题标题】:Getting static value after deserialization反序列化后获取静态值
【发布时间】: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


【解决方案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() 方法),因此其静态字段也将正确初始化为其默认值。

【讨论】:

  • 值“My Company”不会序列化,在反序列化过程中,会创建新的Employee Object(与我们序列化的不同),对company没有任何价值;那么它应该打印 null。
  • 您似乎在混淆“对公司没有价值”。您似乎知道static 隐含为transient,这意味着它没有被序列化和反序列化。因为缺少值并不意味着值将设置为null,但该值不会被修改。尝试将静态块添加到您的 Employee 类中,例如 static{System.out.println("loading Employee");}。你会看到即使你的代码只是反序列化 readObject 也会在内部加载 Employee 类,这意味着它也会初始化它的静态字段,使 company = "My Company"
  • 知道了!感谢 Pshemo。
猜你喜欢
  • 2020-06-07
  • 2014-10-05
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 2018-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多