131. Serializing objects to byte arrays
In Chapter 4, Problem 94, we talked about the serialization/deserialization of Java records, so you should be pretty familiar with these operations. In a nutshell, serialization is the process of transforming an in-memory object into a stream of bytes that can also be stored in memory or written to a file, network, database, external storage, and so on. Deserialization is the reverse process, that is, recreating the object state in memory from the given stream of bytes.
A Java object is serializable if its class implements java.io.Serializable
(or, java.io.Externalizable
). Accomplishing serialization/deserialization takes place via the java.io.ObjectOutputStream
and java.io.ObjectInputStream
classes and writeObject()
/readObject()
methods.
For instance, let’s assume the following Melon
class:
public class Melon implements Serializable {
private final String type;
private final float weight;
// constructor, getters
}
...