Home > database >  Why the output of the filed name is "Tom” instead of "null"?
Why the output of the filed name is "Tom” instead of "null"?

Time:08-03

Note: The field name is static

public void test3() {
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("D:\\store.txt"));
            oos.writeObject(new Person("Tom", 23, 3709));
            oos.flush();

            ois = new ObjectInputStream(new FileInputStream("D:\\store.txt"));
            Object obj = ois.readObject();
            Person p = (Person) obj;
            System.out.println(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

The output is "Person{name='Tom', age=23, id=3709}". But why the static field name is "Tom" instead of null?

CodePudding user response:

The reason is that the Person object is still in the classLoader (having a value of Tom).

If you code set name to null after serialization, then the value would print as null

 Person p = new Person("Tom", 23);
 oos.writeObject(p);
 oos.flush();
 p.setName(null);

Of alternatively, if the write and then read were undertaken as two seperate processes, then also the value would be null

CodePudding user response:

Since the field is static (a poor design, see my comment below), then it's not serialized on the write to the file, so it's not there to be read from the file either. 'name' simply does not participate in serialization.

Meanwhile, since it's static, it retains the value it was given a few lines previously, when you constructed the first Person and named it 'Tom'.

Another way to say this is: your instances of Person each have an 'age' and an 'id'. They do not have each a 'name'. There is only one 'name' in the world.


Why would a class called 'Person' have a field called 'name' that was static? Why should constructing an instance of a Person have the effect of setting every person's name to 'Tom'? That would be a poor way to define the Person class: everyone has the same name.

  • Related