Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 serializing, and it works (surprisingly?) - but I've no idea how.

Here's an example of the class

public class MyValueType implements Serializable {     private final int value;      private transient int derivedValue;      public MyValueType(int value)     {         this.value = value;         this.derivedValue = derivedValue(value);     }      // getters etc... } 

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

(An aside - I noticed this class particularly because IDEA wasn't generating a "no serialVersionUID" inspection warning for this class, yet successfully generated warnings for other classes that I've just made serializable.)

like image 201
mdma Avatar asked May 25 '10 12:05

mdma


People also ask

Can final fields be serialized?

By implementing Serializable the BusinessCard class can already be serialized. To illustrated the problem with final fields we will implement the serialization and deserialization methods writeObject() and readObject() by hand. Serializing the data of our BusinessCard class is straightforward.

Why constructor is not called during deserialization in Java?

The deserialization process does not use the object's constructor - the object is instantiated without a constructor and initialized using the serialized instance data.

Can final variable be serialized in Java?

transient and final : final variables are directly serialized by their values, so there is no use/impact of declaring final variable as transient.

How does serialization and deserialization work in Java?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.


1 Answers

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

like image 148
Michael Borgwardt Avatar answered Oct 04 '22 13:10

Michael Borgwardt