Top Description Inners Fields Constructors Methods
java.io

public Class ObjectInputStream

extends InputStream
implements ObjectInput, ObjectStreamConstants
Class Inheritance
All Implemented Interfaces
java.io.ObjectStreamConstants, java.io.ObjectInput, java.lang.AutoCloseable, java.io.DataInput
Known Direct Subclasses
javax.crypto.extObjectInputStream
Imports
java.io.ObjectInputFilter.Config, .ObjectStreamClass.RecordSupport, java.lang.System.Logger, java.lang.invoke.MethodHandle, java.lang.reflect.Array, .InvocationHandler, .Modifier, .Proxy, java.security.AccessControlContext, .AccessController, .PrivilegedAction, .PrivilegedActionException, .PrivilegedExceptionAction, java.util.Arrays, .Map, .Objects, jdk.internal.access.SharedSecrets, jdk.internal.event.DeserializationEvent, jdk.internal.misc.Unsafe, jdk.internal.util.ByteArray, sun.reflect.misc.ReflectUtil, sun.security.action.GetBooleanAction, .GetIntegerAction

An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.

Warning

Deserialization of untrusted data is inherently dangerous and should be avoided. Untrusted data should be carefully validated according to the "Serialization and Deserialization" section of the Secure Coding Guidelines for Java SE. Serialization Filtering describes best practices for defensive use of serial filters.

The key to disabling deserialization attacks is to prevent instances of arbitrary classes from being deserialized, thereby preventing the direct or indirect execution of their methods. ObjectInputFilter describes how to use filters and ObjectInputFilter.Config describes how to configure the filter and filter factory. Each stream has an optional deserialization filter to check the classes and resource limits during deserialization. The JVM-wide filter factory ensures that a filter can be set on every ObjectInputStream and every object read from the stream can be checked. The ObjectInputStream constructors invoke the filter factory to select the initial filter which may be updated or replaced by setObjectInputFilter.

If an ObjectInputStream has a filter, the ObjectInputFilter can check that the classes, array lengths, number of references in the stream, depth, and number of bytes consumed from the input stream are allowed and if not, can terminate deserialization.

ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.

ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms.

Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams.

The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java, strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the expected type.

Primitive data types can be read from the stream using the appropriate method on DataInput.

The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those objects to be read from the stream as necessary. Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten.

Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's most specific class.

For example to read from a stream as written by the example in ObjectOutputStream:

try (FileInputStream fis = new FileInputStream("t.tmp"); ObjectInputStream ois = new ObjectInputStream(fis)) { String label = (String) ois.readObject(); LocalDateTime dateTime = (LocalDateTime) ois.readObject(); // Use label and dateTime } catch (Exception ex) { // handle exception }
try (FileInputStream fis = new FileInputStream("t.tmp");
     ObjectInputStream ois = new ObjectInputStream(fis)) {
    String label = (String) ois.readObject();
    LocalDateTime dateTime = (LocalDateTime) ois.readObject();
    // Use label and dateTime
} catch (Exception ex) {
    // handle exception
}

Classes control how they are serialized by implementing either the java.io.Serializable or java.io.Externalizable interfaces.

Implementing the Serializable interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read. It automatically traverses references between objects, saving and restoring entire graphs.

Serializable classes that require special handling during the serialization and deserialization process should implement methods with the following signatures:

private void writeObject(java.io.ObjectOutputStream stream) throws IOException; private void readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; private void readObjectNoData() throws ObjectStreamException;
private void writeObject(java.io.ObjectOutputStream stream)
    throws IOException;
private void readObject(java.io.ObjectInputStream stream)
    throws IOException, ClassNotFoundException;
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 readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput.

Any attempt to read object data which exceeds the boundaries of the custom data written by the corresponding writeObject method will cause an OptionalDataException to be thrown with an eof field value of true. Non-object reads which exceed the end of the allotted data will reflect the end of data in the same way that they would indicate the end of the stream: bytewise reads will return -1 as the byte read or number of bytes read, and primitive reads will throw EOFExceptions. If there is no corresponding writeObject method, then the end of default serialized data marks the end of the allotted data.

Primitive and object read calls issued from within a readExternal method behave in the same manner--if the stream is already positioned at the end of data written by the corresponding writeExternal method, object reads will throw OptionalDataExceptions with eof set to true, bytewise reads will return -1, and primitive reads will throw EOFExceptions. Note that this behavior does not hold for streams written with the old ObjectStreamConstants.PROTOCOL_VERSION_1 protocol, in which the end of data written by writeExternal methods is not demarcated, and hence cannot be detected.

The readObjectNoData method is responsible for initializing the state of the object for its particular class in the event that the serialization stream does not list the given class as a superclass of the object being deserialized. This may occur in cases where the receiving party uses a different version of the deserialized instance's class than the sending party, and the receiver's version extends classes that are not extended by the sender's version. This may also occur if the serialization stream has been tampered; hence, readObjectNoData is useful for initializing deserialized objects properly despite a "hostile" or incomplete source stream.

Serialization does not read or assign values to 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.

Any exception that occurs while deserializing an object will be caught by the ObjectInputStream and abort the reading 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 deserialized 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 deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the static method Enum.valueOf(Class, String) with the enum constant's base type and the received constant name as arguments. 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 deserialized cannot be customized: any class-specific readObject, readObjectNoData, and readResolve methods defined by enum types are ignored during deserialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L.

Records are serialized differently than ordinary serializable or externalizable objects. During deserialization the record's canonical constructor is invoked to construct the record object. Certain serialization-related methods, such as readObject and writeObject, are ignored for serializable records. See Java Object Serialization Specification, Section 1.13, "Serialization of Records" for additional information.

Authors
Mike Warres, Roger Riggs
Since
1.1
External Specification
Java Object Serialization Specification
See Also
java.io.DataInput, java.io.ObjectOutputStream, java.io.Serializable, Java Object Serialization Specification, Section 3, "Object Input Classes"

Nested and Inner Type Summary

Modifier and TypeClass and Description
private class
ObjectInputStream.BlockDataInputStream

Input stream with two modes: in default mode, inputs data written in the same format as DataOutputStream; in "block data" mode, inputs data bracketed by block data markers (see object serialization specification for details).

private static class
private class
ObjectInputStream.FieldValues

Default GetField implementation.

pack-priv static class
ObjectInputStream.FilterValues

Hold a snapshot of values to be passed to an ObjectInputFilter.

public abstract static class
ObjectInputStream.GetField

Provide access to the persistent fields read from the input stream.

private static class
ObjectInputStream.HandleTable

Unsynchronized table which tracks wire handle to object mappings, as well as ClassNotFoundExceptions associated with deserialized objects.

private static class
private static class
ObjectInputStream.PeekInputStream

Input stream supporting single-byte peek operations.

private static class
ObjectInputStream.ValidationList

Prioritized list of callbacks to be performed once object graph has been completely deserialized.

Field Summary

Modifier and TypeField and Description
private final ObjectInputStream.BlockDataInputStream
bin

filter stream for handling block data conversion

private boolean
closed

whether stream is closed

private SerialCallbackContext
curContext

Context during upcalls to class-defined readObject methods; holds object currently being deserialized and descriptor for current class.

private boolean
defaultDataEnd

flag set when at end of field value block with no TC_ENDBLOCKDATA

private long
depth

recursion depth

private final boolean
enableOverride

if true, invoke readObjectOverride() instead of readObject()

private boolean
enableResolve

if true, invoke resolveObject()

private final ObjectInputStream.HandleTable
handles

wire handle -> obj/exception map

private static final int
NULL_HANDLE

handle value representing null

private int
passHandle

scratch field for passing handle values up/down call stack

private ObjectInputFilter
serialFilter

Filter of class descriptors and classes read from the stream; may be null.

private boolean
streamFilterSet

True if the stream-specific filter has been set; initially false.

private long
totalObjectRefs

Total number of references to any type of object, class, enum, proxy, etc.

private static final Unsafe
private static final Object
unsharedMarker

marker for unshared objects in internal handle table

private final ObjectInputStream.ValidationList
vlist

validation callback list

Constructor Summary

AccessConstructor and Description
public
ObjectInputStream(InputStream
input stream to read from
in
)

Creates an ObjectInputStream that reads from the specified InputStream.

protected
ObjectInputStream()

Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.

Method Summary

Modifier and TypeMethod and Description
private static Boolean
auditSubclass(Class<?> subcl)

Performs reflective checks on given subclass to verify that it doesn't override security-sensitive non-final methods.

public int

Returns:

the number of available bytes.
available
()

Overrides java.io.InputStream.available.

Implements java.io.ObjectInput.available.

Returns the number of bytes that can be read without blocking.

private void
checkArray(Class<?>
the array type
arrayType
,
int
the array length
arrayLength
)

Checks the given array type and length to ensure that creation of such an array is permitted by this ObjectInputStream.

private Object
checkResolve(Object obj)

If resolveObject has been enabled and given object does not have an exception associated with it, calls resolveObject to determine replacement for object, and updates handle table accordingly.

private void
clear()

Clears internal data structures.

private static Object
cloneArray(Object array)

Method for cloning arrays in case of using unsharing reading

public void
close()

Overrides java.io.InputStream.close.

Implements java.io.ObjectInput.close, java.io.Closeable.close.

Closes the input stream.

public void
defaultReadObject()

Read the non-static and non-transient fields of the current class from this stream.

protected boolean

Returns:

the previous setting before this method was invoked
enableResolveObject
(boolean
true for enabling use of resolveObject for every object being deserialized
enable
)

Enables the stream to do replacement of objects read from the stream.

private void
filterCheck(Class<?>
the class; may be null
clazz
,
int
the array length requested; use -1 if not creating an array
arrayLength
)

Invokes the deserialization filter if non-null.

private void
freeze()

Performs a "freeze" action, required to adhere to final field semantics.

public final ObjectInputFilter

Returns:

the deserialization filter for the stream; may be null
getObjectInputFilter
()

Returns the deserialization filter for this stream.

private void
handleReset()

If recursion depth is 0, clears internal data structures; otherwise, throws a StreamCorruptedException.

private boolean
private static ClassLoader
latestUserDefinedLoader()

Returns the first non-null and non-platform class loader (not counting class loaders of generated reflection implementation classes) up the execution stack, or the platform class loader if only code from the bootstrap and platform class loader is on the stack.

public int

Returns:

the byte read, or -1 if the end of the stream is reached.
read
()

Implements abstract java.io.InputStream.read.

Implements java.io.ObjectInput.read.

Reads a byte of data.

public int

Returns:

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.
read
(byte[]
the buffer into which the data is read
buf
,
int
the start offset in the destination array buf
off
,
int
the maximum number of bytes read
len
)

Overrides java.io.InputStream.read.

Implements java.io.ObjectInput.read.

Reads into an array of bytes.

private Object
readArray(boolean unshared)

Reads in and returns array object, or null if array class is unresolvable.

public boolean

Returns:

the boolean read.
readBoolean
()

Implements java.io.DataInput.readBoolean.

Reads in a boolean.

public byte

Returns:

the 8-bit byte read.
readByte
()

Implements java.io.DataInput.readByte.

Reads an 8-bit byte.

public char

Returns:

the 16-bit char read.
readChar
()

Implements java.io.DataInput.readChar.

Reads a 16-bit char.

private Class<?>
readClass(boolean unshared)

Reads in and returns class object.

private ObjectStreamClass
readClassDesc(boolean unshared)

Reads in and returns (possibly null) class descriptor.

protected ObjectStreamClass

Returns:

the class descriptor read
readClassDescriptor
()

Read a class descriptor from the serialization stream.

public double

Returns:

the 64-bit double read.
readDouble
()

Implements java.io.DataInput.readDouble.

Reads a 64-bit double.

private Enum<?>
readEnum(boolean unshared)

Reads in and returns enum constant, or null if enum type is unresolvable.

private void
readExternalData(Externalizable obj, ObjectStreamClass desc)

If obj is non-null, reads externalizable data by invoking readExternal() method of obj; otherwise, attempts to skip over externalizable data.

private IOException
readFatalException()

Reads in and returns IOException that caused serialization to abort.

public ObjectInputStream.GetField

Returns:

the GetField object representing the persistent fields of the object being deserialized
readFields
()

Reads the persistent fields from the stream and makes them available by name.

public float

Returns:

the 32-bit float read.
readFloat
()

Implements java.io.DataInput.readFloat.

Reads a 32-bit float.

public void
readFully(byte[]
the buffer into which the data is read
buf
)

Implements java.io.DataInput.readFully.

Reads bytes, blocking until all bytes are read.

public void
readFully(byte[]
the buffer into which the data is read
buf
,
int
the start offset into the data array buf
off
,
int
the maximum number of bytes to read
len
)

Implements java.io.DataInput.readFully.

Reads bytes, blocking until all bytes are read.

private Object
readHandle(boolean unshared)

Reads in object handle, sets passHandle to the read handle, and returns object associated with the handle.

public int

Returns:

the 32-bit integer read.
readInt
()

Implements java.io.DataInput.readInt.

Reads a 32-bit int.

public String

Returns:

a String copy of the line.
readLine
()

Implements java.io.DataInput.readLine.

Deprecated This method does not properly convert bytes to characters. see DataInputStream for the details and alternatives.

Reads in a line that has been terminated by a \n, \r, \r\n or EOF.

public long

Returns:

the read 64-bit long.
readLong
()

Implements java.io.DataInput.readLong.

Reads a 64-bit long.

private ObjectStreamClass
readNonProxyDesc(boolean unshared)

Reads in and returns class descriptor for a class that is not a dynamic proxy class.

private Object
readNull()

Reads in null code, sets passHandle to NULL_HANDLE and returns null.

public final Object
readObject()

Implements java.io.ObjectInput.readObject.

Read an object from the ObjectInputStream.

private final Object

Returns:

an object of the type
readObject
(Class<?>
the type expected; either Object.class or String.class
type
)

Internal method to read an object from the ObjectInputStream of the expected type.

private Object
readObject0(Class<?>
a type expected to be deserialized; non-null
type
,
boolean
true if the object can not be a reference to a shared object, otherwise false
unshared
)

Underlying readObject implementation.

protected Object

Returns:

the Object read from the stream.
readObjectOverride
()

This method is called by trusted subclasses of ObjectInputStream that constructed ObjectInputStream using the protected no-arg constructor.

private Object
readOrdinaryObject(boolean unshared)

Reads and returns "ordinary" (i.e., not a String, Class, ObjectStreamClass, array, or enum constant) object, or null if object's class is unresolvable (in which case a ClassNotFoundException will be associated with object's handle).

private ObjectStreamClass
readProxyDesc(boolean unshared)

Reads in and returns class descriptor for a dynamic proxy class.

private Object
readRecord(ObjectStreamClass desc)

Reads a record.

private void
readSerialData(Object obj, ObjectStreamClass desc)

Reads (or attempts to skip, if obj is null or is tagged with a ClassNotFoundException) instance data for each serializable class of object in stream, from superclass to subclass.

public short

Returns:

the 16-bit short read.
readShort
()

Implements java.io.DataInput.readShort.

Reads a 16-bit short.

protected void
readStreamHeader()

The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers.

private String

Returns:

the String read
readString
()

Reads a String and only a string.

private String
readString(boolean unshared)

Reads in and returns new string.

pack-priv String
readTypeString()

Reads string without allowing it to be replaced in stream.

public Object

Returns:

reference to deserialized object
readUnshared
()

Reads an "unshared" object from the ObjectInputStream.

public int

Returns:

the 8-bit byte read.
readUnsignedByte
()

Implements java.io.DataInput.readUnsignedByte.

Reads an unsigned 8-bit byte.

public int

Returns:

the 16-bit short read.
readUnsignedShort
()

Implements java.io.DataInput.readUnsignedShort.

Reads an unsigned 16-bit short.

public String

Returns:

the String.
readUTF
()

Implements java.io.DataInput.readUTF.

Reads a String in modified UTF-8 format.

public void
registerValidation(ObjectInputValidation
the object to receive the validation callback.
obj
,
int
controls the order of callbacks; zero is a good default. Use higher numbers to be called back earlier, lower numbers for later callbacks. Within a priority, callbacks are processed in no particular order.
prio
)

Register an object to be validated before the graph is returned.

protected Class<?>

Returns:

a Class object corresponding to desc
resolveClass
(ObjectStreamClass
an instance of class ObjectStreamClass
desc
)

Load the local class equivalent of the specified stream class description.

protected Object

Returns:

the substituted object
resolveObject
(Object
object to be substituted
obj
)

This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization.

protected Class<?>

Returns:

a proxy class for the specified interfaces
resolveProxyClass
(String[]
the list of interface names that were deserialized in the proxy class descriptor
interfaces
)

Returns a proxy class that implements the interfaces named in a proxy class descriptor; subclasses may implement this method to read custom data from the stream along with the descriptors for dynamic proxy classes, allowing them to use an alternate loading mechanism for the interfaces and the proxy class.

public final void
setObjectInputFilter(ObjectInputFilter
the filter, may be null
filter
)

Set the deserialization filter for the stream.

public int

Returns:

the actual number of bytes skipped.
skipBytes
(int
the number of bytes to be skipped
len
)

Implements java.io.DataInput.skipBytes.

Skips bytes.

private void
skipCustomData()

Skips over all block data and objects until TC_ENDBLOCKDATA is encountered.

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.

Inherited from java.io.InputStream:
markmarkSupportednullInputStreamreadreadAllBytesreadNBytesreadNBytesresetskipskipNBytestransferTo