简体   繁体   中英

Getting static value after deserialization

Please clear my understanding why I am getting of value of company after deserialization. I know "Statics are implicitly transient, so we don't need to declare them as such."

    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();
    }


    }

Value of static field company was set first time you used Employee class. In your case it would be in line:

Employee e = new Employee("John");

This value didn't change since it wasn't serialized and deserialized so it stayed the same, which means

System.out.println(e1.name + " " + e1.company);

prints John My Company .


But even if you remove lines

Employee e = new Employee("John");
serializeObject(e);

from your code, and invoke only

public static void main(String[] args) throws Exception {
    Employee e1 = deserializeObject(); // assume deserialize works fine
    System.out.println(e1.name + " " + e1.company);
}

Employee class will still be loaded inside deserializeObject (by oos.readObject() method) so its static fields will also be properly initialized to its default values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM