I created a Class with a private constructor having one parameter which initializes a private attribute.
An object of this class can be serialized and deserialized properly with the ObjectInputStream/ObjectOutputStream class.
This isn't possible with json serialization/deserialization because the class has no getters, no setters and no public default constructor.
So I am wondering how this works. I know a Java method can access the private elements of an object via introspection, but with output stream deserialization, how can Java successfully instantiate the object without a default constructor it doesn't know the value of the parameters used to create it?
Here is the code for which I don't understand the mechanism:
public class Main implements Serializable {
private int number;
private Main(int number){
this.number = number;
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Main main = new Main(12);
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("file.bin"));
outputStream.writeObject(main);
outputStream.close();
ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("file.bin"));
Main main2 = (Main) objectInputStream.readObject();
objectInputStream.close();
System.out.println(main2.number); // 12
}
}