Class: java.io.ObjectInputStream
- public class ObjectInputStream
- extends InputStream
- implements ObjectInput, ObjectStreamConstants
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:
FileInputStream fis = new FileInputStream("t.tmp");
ObjectInputStream ois = new ObjectInputStream(fis);
int i = ois.readInt();
String today = (String) ois.readObject();
Date date = (Date) ois.readObject();
ois.close();
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 the following methods:
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 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.
Inheritance
Superclass tree:- java.lang.Object
- java.io.InputStream
- java.io.ObjectInputStream
Methods
-
ObjectInputStreamtop
protected ObjectInputStream() throws IOException, SecurityExceptionProvide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.If there is a security manager installed, this method first calls the security manager's
checkPermissionmethod with theSerializablePermission("enableSubclassImplementation")permission to ensure it's ok to enable subclassing. -
ObjectInputStreamtop
public ObjectInputStream(InputStream in) throws IOExceptionCreates an ObjectInputStream that reads from the specified InputStream. A serialization stream header is read from the stream and verified. This constructor will block until the corresponding ObjectOutputStream has written and flushed the header.If a security manager is installed, this constructor will check for the "enableSubclassImplementation" SerializablePermission when invoked directly or indirectly by the constructor of a subclass which overrides the ObjectInputStream.readFields or ObjectInputStream.readUnshared methods.
-
availabletop
public int available() throws IOExceptionReturns the number of bytes that can be read without blocking.- Specified by:
- available from ObjectInput
- Override hierarchy:
- available from InputStream
-
closetop
public void close() throws IOExceptionCloses the input stream. Must be called to release any resources associated with the stream.- Specified by:
- close from ObjectInput
- close from Closeable
- Override hierarchy:
- close from InputStream
-
defaultReadObjecttop
public void defaultReadObject() throws IOException, ClassNotFoundExceptionRead the non-static and non-transient fields of the current class from this stream. This may only be called from the readObject method of the class being deserialized. It will throw the NotActiveException if it is called otherwise. -
enableResolveObjecttop
protected boolean enableResolveObject(boolean enable) throws SecurityExceptionEnable the stream to allow objects read from the stream to be replaced. When enabled, the resolveObject method is called for every object being deserialized.If enable is true, and there is a security manager installed, this method first calls the security manager's
checkPermissionmethod with theSerializablePermission("enableSubstitution")permission to ensure it's ok to enable the stream to allow objects read from the stream to be replaced. -
readtop
public int read() throws IOExceptionReads a byte of data. This method will block if no input is available.- Specified by:
- read from ObjectInput
- Override hierarchy:
- read from InputStream
-
readtop
public int read(byte[] buf, int off, int len) throws IOExceptionReads into an array of bytes. This method will block until some input is available. Consider using java.io.DataInputStream.readFully to read exactly 'length' bytes.- Specified by:
- read from ObjectInput
- Override hierarchy:
- read from InputStream
-
readBooleantop
public boolean readBoolean() throws IOExceptionReads in a boolean.- Specified by:
- readBoolean from DataInput
-
readBytetop
public byte readByte() throws IOExceptionReads an 8 bit byte. -
readChartop
public char readChar() throws IOExceptionReads a 16 bit char. -
readClassDescriptortop
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundExceptionRead a class descriptor from the serialization stream. This method is called when the ObjectInputStream expects a class descriptor as the next item in the serialization stream. Subclasses of ObjectInputStream may override this method to read in class descriptors that have been written in non-standard formats (by subclasses of ObjectOutputStream which have overridden thewriteClassDescriptormethod). By default, this method reads class descriptors according to the format defined in the Object Serialization specification. -
readDoubletop
public double readDouble() throws IOExceptionReads a 64 bit double.- Specified by:
- readDouble from DataInput
-
readFieldstop
Reads the persistent fields from the stream and makes them available by name. -
readFloattop
public float readFloat() throws IOExceptionReads a 32 bit float. -
readFullytop
public void readFully(byte[] buf) throws IOExceptionReads bytes, blocking until all bytes are read. -
readFullytop
public void readFully(byte[] buf, int off, int len) throws IOExceptionReads bytes, blocking until all bytes are read. -
readInttop
public int readInt() throws IOExceptionReads a 32 bit int. -
readLinetop
Reads in a line that has been terminated by a \n, \r, \r\n or EOF. -
readLongtop
public long readLong() throws IOExceptionReads a 64 bit long. -
readObjecttop
public final Object readObject() throws IOException, ClassNotFoundExceptionRead an object from the ObjectInputStream. The class of the object, the signature of the class, and the values of the non-transient and non-static fields of the class and all of its supertypes are read. Default deserializing for a class can be overriden using the writeObject and readObject methods. Objects referenced by this object are read transitively so that a complete equivalent graph of objects is reconstructed by readObject.The root object is completely restored when all of its fields and the objects it references are completely restored. At this point the object validation callbacks are executed in order based on their registered priorities. The callbacks are registered by objects (in the readObject special methods) as they are individually restored.
Exceptions are thrown for problems with the InputStream and for classes that should not be deserialized. All exceptions are fatal to the InputStream and leave it in an indeterminate state; it is up to the caller to ignore or recover the stream state.
- Specified by:
- readObject from ObjectInput
-
readObjectOverridetop
protected Object readObjectOverride() throws IOException, ClassNotFoundExceptionThis method is called by trusted subclasses of ObjectOutputStream that constructed ObjectOutputStream using the protected no-arg constructor. The subclass is expected to provide an override method with the modifier "final". -
readShorttop
public short readShort() throws IOExceptionReads a 16 bit short. -
readStreamHeadertop
protected void readStreamHeader() throws IOException, StreamCorruptedExceptionThe readStreamHeader method is provided to allow subclasses to read and verify their own stream headers. It reads and verifies the magic number and version number. -
readUTFtop
public String readUTF() throws IOExceptionReads a String in modified UTF-8 format. -
readUnsharedtop
public Object readUnshared() throws IOException, ClassNotFoundExceptionReads an "unshared" object from the ObjectInputStream. This method is identical to readObject, except that it prevents subsequent calls to readObject and readUnshared from returning additional references to the deserialized instance obtained via this call. Specifically:- If readUnshared is called to deserialize a back-reference (the stream representation of an object which has been written previously to the stream), an ObjectStreamException will be thrown.
- If readUnshared returns successfully, then any subsequent attempts to deserialize back-references to the stream handle deserialized by readUnshared will cause an ObjectStreamException to be thrown.
ObjectInputStream subclasses which override this method can only be constructed in security contexts possessing the "enableSubclassImplementation" SerializablePermission; any attempt to instantiate such a subclass without this permission will cause a SecurityException to be thrown.
-
readUnsignedBytetop
public int readUnsignedByte() throws IOExceptionReads an unsigned 8 bit byte.- Specified by:
- readUnsignedByte from DataInput
-
readUnsignedShorttop
public int readUnsignedShort() throws IOExceptionReads an unsigned 16 bit short.- Specified by:
- readUnsignedShort from DataInput
-
registerValidationtop
public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectExceptionRegister an object to be validated before the graph is returned. While similar to resolveObject these validations are called after the entire graph has been reconstituted. Typically, a readObject method will register the object with the stream so that when all of the objects are restored a final set of validations can be performed. -
resolveClasstop
Load the local class equivalent of the specified stream class description. Subclasses may implement this method to allow classes to be fetched from an alternate source.The corresponding method in
ObjectOutputStreamisannotateClass. This method will be invoked only once for each unique class in the stream. This method can be implemented by subclasses to use an alternate loading mechanism but must return aClassobject. Once returned, if the class is not an array class, its serialVersionUID is compared to the serialVersionUID of the serialized class, and if there is a mismatch, the deserialization fails and an java.io.InvalidClassException is thrown.The default implementation of this method in
ObjectInputStreamreturns the result of callingClass.forName(desc.getName(), false, loader)whereloaderis determined as follows: if there is a method on the current thread's stack whose declaring class was defined by a user-defined class loader (and was not a generated to implement reflective invocations), thenloaderis class loader corresponding to the closest such method to the currently executing frame; otherwise,loaderisnull. If this call results in aClassNotFoundExceptionand the name of the passedObjectStreamClassinstance is the Java language keyword for a primitive type or void, then theClassobject representing that primitive type or void will be returned (e.g., anObjectStreamClasswith the name"int"will be resolved toInteger.TYPE). Otherwise, theClassNotFoundExceptionwill be thrown to the caller of this method. -
resolveObjecttop
This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization. Replacing objects is disabled until enableResolveObject is called. The enableResolveObject method checks that the stream requesting to resolve object can be trusted. Every reference to serializable objects is passed to resolveObject. To insure that the private state of objects is not unintentionally exposed only trusted streams may use resolveObject.This method is called after an object has been read but before it is returned from readObject. The default resolveObject method just returns the same object.
When a subclass is replacing objects it must insure that the substituted object is compatible with every field where the reference will be stored. Objects whose type is not a subclass of the type of the field or array element abort the serialization by raising an exception and the object is not be stored.
This method is called only once when each object is first encountered. All subsequent references to the object will be redirected to the new object.
-
resolveProxyClasstop
protected Class<?> resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundExceptionReturns 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.This method is called exactly once for each unique proxy class descriptor in the stream.
The corresponding method in
ObjectOutputStreamisannotateProxyClass. For a given subclass ofObjectInputStreamthat overrides this method, theannotateProxyClassmethod in the corresponding subclass ofObjectOutputStreammust write any data or objects read by this method.The default implementation of this method in
ObjectInputStreamreturns the result of callingProxy.getProxyClasswith the list ofClassobjects for the interfaces that are named in theinterfacesparameter. TheClassobject for each interface nameiis the value returned by callingClass.forName(i, false, loader)whereloaderis that of the first non-nullclass loader up the execution stack, ornullif no non-nullclass loaders are on the stack (the same class loader choice used by theresolveClassmethod). Unless any of the resolved interfaces are non-public, this same value ofloaderis also the class loader passed toProxy.getProxyClass; if non-public interfaces are present, their class loader is passed instead (if more than one non-public interface class loader is encountered, anIllegalAccessErroris thrown). IfProxy.getProxyClassthrows anIllegalArgumentException,resolveProxyClasswill throw aClassNotFoundExceptioncontaining theIllegalArgumentException. -
skipBytestop
public int skipBytes(int len) throws IOExceptionSkips bytes.
