How does deserialization work?

As far as I understand, the constructor of the class whose object is being serialized is not called, and the constructor is no-arg of the 1st non-serializable constructor. Now consider the following code

public class SerializeDemo implements Serializable {

private String name;
int age;    //default 0

public SerializeDemo(String name, boolean setAge){
    this.name = name;
    if(setAge){
        this.age = 18;
    }
}

@Override
public String toString() {
    return "Name is " + name + " and age is " + age;
}

public static void main(String args[]) throws IOException, ClassNotFoundException {

    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("//home//aniket//Desktop//serializedObjects.txt")));
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("//home//aniket//Desktop//serializedObjects.txt")));
    SerializeDemo sd = new SerializeDemo("Test",true);
    System.out.println("Before Serialization : " + sd);
    oos.writeObject(sd);
    SerializeDemo sdCopy = (SerializeDemo)ois.readObject();
    System.out.println("After Deserialization : " + sdCopy);
}
}

and exit (as expected)

Before Serialization : Name is Test and age is 18
After Deserialization : Name is Test and age is 18

Now a non-serializable superclass having a no-arg constructor is Object (correct me if I am wrong). Therefore, basically the constructor of SerializeDemo is not called.

Now that the object is created during deserialization, it will try to rebuild the state of the instance. Therefore, he will set the age to 18 years.

Question: how?

I intentionally did not provide the installer. As in the previous discussion, this constructor is called. So how is it installed? (The same goes for the name)

+4
2

ObjectInputStream. , , . , .

+2

, no-arg, Object.

.

SerializeDemo .

.

, , . 18 .

.

: ?

... .

. Class Field . Field, Field.set(...) .

( , , , JVM . ...)

+3

All Articles