0

Consider a code:

public class MyDto implements Serializable {
    private String myField;
    public MyDto (String myField) {
        this.myField = myField;
    } 
}

As I see this code works (I hope), but I have no idea how java serialization/deserialization construct object before it sets fields. Any idea?

About duplication

I have not found any constructor or immutable key words in this page. So this question is a bit different. Also this describes difference between json/xml etc not some specific feature to java serialization.

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 1
    When you're calling new MyDto("foo"), the constructor is invoked, and it has access to `this`, which is the MyDto being initialized. So the JVM created a MyDto object before setting its fields, too. My point is that serialization is implemented by the JVM, and is thus not bound by the rules of Java code. – JB Nizet Oct 28 '18 at 12:39
  • It doesn't make any difference. The jvm creates an empty object and then uses dark magic to get the values into that object. It does not matter whether that object is immutable or not. – GhostCat Oct 28 '18 at 12:45
  • When Java de-serializes MyDto instance, that one argument constructor is not called, like @JBNizet pointed out. –  Oct 28 '18 at 12:48
  • Using reflection, it creates an instance of the object and then sets all the fields. It can do this even if the field – Peter Lawrey Oct 28 '18 at 18:05
  • Using Java reflection, a serialization library can access all the fields even if private, create an instance, even if no default constructor and it can set final fields. – Peter Lawrey Oct 28 '18 at 18:06

0 Answers0