Externalizable in Java
To change the default serialization/deserialization behavior you can implement the java.io.Externalizable interface that allows custom serialization logic to be applied. The way to serialize and deserialize is described in the writeExternal() and readExternal() methods. During deserialization, the constructor without parameters is called, and then the readExternal method is called on the created object.
If a serializable object has one of the following methods implemented, then the serialization mechanism will use it, rather than the default method:
- writeObject() - writing an object to a stream
- readObject() - reading an object from the stream
- writeReplace() - allows you to replace yourself with an instance of another class before writing
- readResolve() - allows you to replace another object with itself after reading
Exclude fields from serialization
The transient keyword can be used to control serialization when defining fields, thus excluding the fields from the general serialization process.
Class fields marked with the transient modifier are not serialized.
Typically, such fields store an intermediate state of the object, which, for example, is easier to calculate. Another example of such a field is a reference to an instance of an object that does not require serialization or cannot be serialized.
Impact of static and final field modifiers on serializability
With standard serialization, fields with the static modifier are not serialized. Accordingly, after deserialization, this field does not change its value. When using the Externalizable implementation, it is possible to serialize and deserialize a static field, but it is not recommended - this can be accompanied by subtle errors.
Final fields are serialized just like normal fields. With one exception - they cannot be deserialized when using Externalizable, since final fields must be initialized in the constructor, and after that, it will be impossible to change the value of this field in readExternal(). Accordingly, if you need to serialize an object with a final field, you must use only standard serialization.
How to prevent serialization?
To prevent automatic serialization, you can override private methods to throw a NotSerializableException exception.
private void writeObject(ObjectOutputStream out) throws IOException {
throw new NotSerializableException();
}
private void readObject(ObjectInputStream in) throws IOException {
throw new NotSerializableException();
}
Any attempt to write or read this object will now throw an exception.
Read also:
Comments
Post a Comment