The Serializable Interface

Unlimited serialization would introduce some security problems. For one thing, it allows unrestricted access to an object’s private fields. By chaining an object output stream to a byte array output stream, a hacker can convert an object into a byte array. The byte array can be manipulated and modified without any access protection or security manager checks. Then the byte array can be reconstituted into a Java object by using it as the source of a byte array input stream.

Security isn’t the only potential problem. Some objects exist only as long as the current program is running. A java.net.Socket object represents an active connection to a remote host. Suppose a socket is serialized to a file, and the program exits. Later the socket is deserialized from the file in a new program—but the connection it represents no longer exists. Similar problems arise with file descriptors, I/O streams, and many more classes.

For these and other reasons, Java does not allow instances of arbitrary classes to be serialized. You can only serialize instances of classes that implement the java.io.Serializable interface. By implementing this interface, a class indicates that it may be serialized without undue problems.

public interface Serializable

This interface does not declare any methods or fields; it serves purely to indicate that a class may be serialized. You should recall, however, that subclasses of a class that implements a particular interface also implement that interface ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.