How does java serialization deserialize final fields when no default constructor specified?

前端 未结 3 726
伪装坚强ぢ
伪装坚强ぢ 2020-12-05 17:00

I have an class defining an immutable value type that I now need to serialize. The immutability comes from the final fields which are set in the constructor. I\'ve tried ser

相关标签:
3条回答
  • 2020-12-05 17:26

    Both Michael and Stephen gave you an excellent answer, I just want to caution you about transient fields.

    If default value (null for references, 0 for primitives ) is not acceptable for them after deserialization then you have to provide your version of readObject and initialize it there.

        private void readObject (
                final ObjectInputStream s
            ) throws
                ClassNotFoundException,
                IOException
        {
            s.defaultReadObject( );
    
            // derivedValue is still 0
            this.derivedValue = derivedValue( value );
        }
    
    0 讨论(0)
  • 2020-12-05 17:39

    Given that the class doesn't have a no arg constructor, how can it be instantiated and the final field set?

    Some nasty black magic happens. There is a backdoor in the JVM that allows an object to be created without invoking any constructor. The fields of the new object are first initialized to their default values (false, 0, null, etc), and then the object deserialization code populates the fields with values from the object stream.

    (Now that Java is open sourced, you can read the code that does this ... and weep!)

    0 讨论(0)
  • 2020-12-05 17:46

    Deserialization is implemented by the JVM on a level below the basic language constructs. Specifically, it does not call any constructor.

    0 讨论(0)
提交回复
热议问题