Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.
The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.
Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
For example to write an object that can be read by the example in
ObjectInputStream
:
try (FileOutputStream fos = new FileOutputStream("t.tmp"); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject("Today"); oos.writeObject(LocalDateTime.now()); } catch (Exception ex) { // handle exception }
Serializable classes that require special handling during the serialization and deserialization process should implement methods with the following signatures:
private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; private void writeObject(java.io.ObjectOutputStream stream) throws IOException; private void readObjectNoData() throws ObjectStreamException;
The method name, modifiers, return type, and number and type of parameters must match exactly for the method to be used by serialization or deserialization. The methods should only be declared to throw checked exceptions consistent with these signatures.
The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object's 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.
Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state.
Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process.
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
Enum constants are serialized differently than ordinary serializable or externalizable objects. The serialized form of an enum constant consists solely of its name; field values of the constant are not transmitted. To serialize an enum constant, ObjectOutputStream writes the string returned by the constant's name method. Like other serializable or externalizable objects, enum constants can function as the targets of back references appearing subsequently in the serialization stream. The process by which enum constants are serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L.
Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record. The blocking factor used for a block-data record will be 1024 bytes. Each block-data record will be filled up to 1024 bytes, or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject, defaultWriteObject and writeFields initially terminate any existing block-data record.
Records are serialized differently than ordinary serializable or externalizable objects, see record serialization.
java.io.DataOutput
, java.io.ObjectInputStream
, java.io.Serializable
, java.io.Externalizable
, Java Object Serialization Specification, Section 2, "Object Output Classes"
Modifier and Type | Class and Description |
---|---|
private static class | ObjectOutputStream.
Buffered output stream with two modes: in default mode, outputs data in same format as DataOutputStream; in "block data" mode, outputs data bracketed by block data markers (see object serialization specification for details). |
private static class | |
private static class | ObjectOutputStream.
Stack to keep debug information about the state of the serialization process, for embedding in exception messages. |
private static class | ObjectOutputStream.
Lightweight identity hash table which maps objects to integer handles, assigned in ascending order. |
public abstract static class | ObjectOutputStream.
Provide programmatic access to the persistent fields to be written to ObjectOutput. |
private class | ObjectOutputStream.
Default PutField implementation. |
private static class | ObjectOutputStream.
Lightweight identity hash table which maps objects to replacement objects. |
Modifier and Type | Field and Description |
---|---|
private final ObjectOutputStream. | bout
filter stream for handling block data conversion |
private SerialCallbackContext | curContext
Context during upcalls to class-defined writeObject methods; holds object currently being serialized and descriptor for current class. |
private ObjectOutputStream. | curPut
current PutField object |
private final ObjectOutputStream. | debugInfoStack
custom storage for debug trace info |
private int | depth
recursion depth |
private final boolean | enableOverride
if true, invoke writeObjectOverride() instead of writeObject() |
private boolean | enableReplace
if true, invoke replaceObject() |
private static final boolean | extendedDebugInfo
value of "sun.io.serialization.extendedDebugInfo" property, as true or false for extended information about exception's place |
private final ObjectOutputStream. | handles
obj -> wire handle map |
private byte[] | primVals
buffer for writing primitive field values |
private int | protocol
stream protocol version |
private final ObjectOutputStream. | subs
obj -> replacement obj map |
Access | Constructor and Description |
---|---|
public | ObjectOutputStream(OutputStream
output stream to write to out)Creates an ObjectOutputStream that writes to the specified OutputStream. |
protected | ObjectOutputStream()
Provide a way for subclasses that are completely reimplementing ObjectOutputStream to not have to allocate private data just used by this implementation of ObjectOutputStream. |
Modifier and Type | Method and Description |
---|---|
protected void | annotateClass(Class<?>
the class to annotate custom data for cl)Subclasses may implement this method to allow class data to be stored in the stream. |
protected void | annotateProxyClass(Class<?>
the proxy class to annotate custom data for cl)Subclasses may implement this method to store custom data in the stream along with descriptors for dynamic proxy classes. |
private static Boolean | auditSubclass(Class<?> subcl)
Performs reflective checks on given subclass to verify that it doesn't override security-sensitive non-final methods. |
private void | |
public void | close()
Overrides java. Implements java. Closes the stream. |
private void | defaultWriteFields(Object obj, ObjectStreamClass desc)
Fetches and writes values of serializable fields of given object to stream. |
public void | defaultWriteObject()
Write the non-static and non-transient fields of the current class to this stream. |
protected void | |
protected boolean | Returns: the previous setting before this method was invokedtrue for enabling use of enable)replaceObject for
every object being serializedEnables the stream to do replacement of objects written to the stream. |
public void | flush()
Overrides java. Implements java. Flushes the stream. |
pack-priv int | |
private boolean | |
public ObjectOutputStream. | Returns: an instance of the class Putfield that holds the serializable fieldsRetrieve the object used to buffer persistent fields to be written to the stream. |
protected Object | Returns: the alternate object that replaced the specified onethe object to be replaced obj)This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization. |
public void | |
public void | useProtocolVersion(int
use ProtocolVersion from java.io.ObjectStreamConstants. version)Specify stream protocol version to use when writing the stream. |
private void | verifySubclass()
Verifies that this (possibly subclass) instance can be constructed without violating security constraints: the subclass must not override security-sensitive non-final methods, or else the "enableSubclassImplementation" SerializablePermission is checked. |
public void | write(int
the byte to be written to the stream val)Implements abstract java. Implements java. Writes a byte. |
public void | write(byte[]
the data to be written buf)Overrides java. Implements java. Writes an array of bytes. |
public void | write(byte[]
the data to be written buf, int the start offset in the data off, int the number of bytes that are written len)Overrides java. Implements java. Writes a sub array of bytes. |
private void | writeArray(Object array, ObjectStreamClass desc, boolean unshared)
Writes given array object to stream. |
public void | writeBoolean(boolean
the boolean to be written val)Implements java. Writes a boolean. |
public void | writeByte(int
the byte value to be written val)Implements java. Writes an 8-bit byte. |
public void | writeBytes(String
the String of bytes to be written str)Implements java. Writes a String as a sequence of bytes. |
public void | writeChar(int
the char value to be written val)Implements java. Writes a 16-bit char. |
public void | writeChars(String
the String of chars to be written str)Implements java. Writes a String as a sequence of chars. |
private void | |
private void | writeClassDesc(ObjectStreamClass desc, boolean unshared)
Writes representation of given class descriptor to stream. |
protected void | writeClassDescriptor(ObjectStreamClass
class descriptor to write to the stream desc)Write the specified class descriptor to the ObjectOutputStream. |
public void | writeDouble(double
the double value to be written val)Implements java. Writes a 64-bit double. |
private void | writeEnum(Enum<?> en, ObjectStreamClass desc, boolean unshared)
Writes given enum constant to stream. |
private void | writeExternalData(Externalizable obj)
Writes externalizable data of given object by invoking its writeExternal() method. |
private void | writeFatalException(IOException ex)
Attempts to write to stream fatal IOException that has caused serialization to abort. |
public void | |
public void | writeFloat(float
the float value to be written val)Implements java. Writes a 32-bit float. |
private void | |
public void | writeInt(int
the integer value to be written val)Implements java. Writes a 32-bit int. |
public void | writeLong(long
the long value to be written val)Implements java. Writes a 64-bit long. |
private void | writeNonProxyDesc(ObjectStreamClass desc, boolean unshared)
Writes class descriptor representing a standard (i.e., not a dynamic proxy) class to stream. |
private void | |
public final void | writeObject(Object
the object to be written obj)Implements java. Write the specified object to the ObjectOutputStream. |
private void | |
protected void | writeObjectOverride(Object
object to be written to the underlying stream obj)Method used by subclasses to override the default writeObject method. |
private void | writeOrdinaryObject(Object obj, ObjectStreamClass desc, boolean unshared)
Writes representation of an "ordinary" (i.e., not a String, Class, ObjectStreamClass, array, or enum constant) serializable object to the stream. |
private void | writeProxyDesc(ObjectStreamClass desc, boolean unshared)
Writes class descriptor representing a dynamic proxy class to stream. |
private void | writeRecordData(Object obj, ObjectStreamClass desc)
Writes the record component values for the given record object. |
private void | writeSerialData(Object obj, ObjectStreamClass desc)
Writes instance data for each serializable class of given object, from superclass to subclass. |
public void | writeShort(int
the short value to be written val)Implements java. Writes a 16-bit short. |
protected void | writeStreamHeader()
The writeStreamHeader method is provided so subclasses can append or prepend their own header to the stream. |
private void | writeString(String str, boolean unshared)
Writes given string to stream, using standard or long UTF format depending on string length. |
pack-priv void | |
public void | writeUnshared(Object
object to write to stream obj)Writes an "unshared" object to the ObjectOutputStream. |
public void | writeUTF(String
the String to be written str)Implements java. Primitive data write of this String in modified UTF-8 format. |