class MyClass implements Serializable { transient int myTransient; //Other variables }
When I restore this class I want to initialize myTransient
manually, but otherwise I just want to use the default serialization.
How can I inject an init()
method into the object restore process without re-writing the entire serialization mechanism as it seems like Externalizable
would have me do?
At the time of serialization, if you don't want to save the value of a particular variable in a file, then use the transient keyword. transient private <member variable>; In case you define any data member as transient, it will not be serialized. This is because every field marked as transient will not be serialized.
transient Fields: Variables may be marked transient to indicate that they are not part of the persistent state of an object. For example, you may have fields that are derived from other fields, and should only be done so programmatically, rather than having the state be persisted via serialization.
transient is a variables modifier used in serialization. At the time of serialization, if we don't want to save value of a particular variable in a file, then we use transient keyword. When JVM comes across transient keyword, it ignores original value of the variable and save default value of that variable data type.
If you don't want to serialize otherProperties , then the field should be marked as transient : private transient Map<String, Object> otherProperties; Otherwise, you can change the type of otherProperties to an implementation of Map that implements Serializable , such as HashMap .
Implement a readObject()
method:
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); myTransient = ...; }
From javadoc:
Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;
The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
See also:
Serializable
javadocIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With