0

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
    }
}
user11809641
  • 815
  • 1
  • 11
  • 22
hyper_tecker
  • 11
  • 1
  • 4
  • Depending on the specific JSON serializer (and its config or mappers), private fields can also be serialized by those, so that in itself is nothing special, but yes, Java has special rules and features for object serialization. – Mark Rotteveel Nov 13 '20 at 08:56
  • You (and also the `ObjectInputStream`) can access private constructors using reflection – Smutje Nov 13 '20 at 08:57
  • @Smutje - True, but that doesn't solve the problem, and it isn't how `ObjectInputStream` works. See the source code. – Stephen C Nov 13 '20 at 09:47

0 Answers0