java.lang.Object java.io.InputStream java.io.ObjectInputStream
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.
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 valueOf method of the enum constant's base type with the received constant name as the argument. 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.
|Nested Class Summary|
Provide access to the persistent fields read from the input stream.
|Fields inherited from interface java.io. ObjectStreamConstants|
|baseWireHandle , PROTOCOL_VERSION_1 , PROTOCOL_VERSION_2 , SC_BLOCK_DATA , SC_ENUM , SC_EXTERNALIZABLE , SC_SERIALIZABLE , SC_WRITE_METHOD , STREAM_MAGIC , STREAM_VERSION , SUBCLASS_IMPLEMENTATION_PERMISSION , SUBSTITUTION_PERMISSION , TC_ARRAY , TC_BASE , TC_BLOCKDATA , TC_BLOCKDATALONG , TC_CLASS , TC_CLASSDESC , TC_ENDBLOCKDATA , TC_ENUM , TC_EXCEPTION , TC_LONGSTRING , TC_MAX , TC_NULL , TC_OBJECT , TC_PROXYCLASSDESC , TC_REFERENCE , TC_RESET , TC_STRING|
Provide a way for subclasses that are completely reimplementing ObjectInputStream to not have to allocate private data just used by this implementation of ObjectInputStream.
Creates an ObjectInputStream that reads from the specified InputStream.
Returns the number of bytes that can be read without blocking.
Closes the input stream.
Read the non-static and non-transient fields of the current class from this stream.
Enable the stream to allow objects read from the stream to be replaced.
Reads a byte of data.
(byte buf, int off, int len)
Reads into an array of bytes.
Reads in a boolean.
Reads an 8 bit byte.
Reads a 16 bit char.
Read a class descriptor from the serialization stream.
Reads a 64 bit double.
Reads the persistent fields from the stream and makes them available by name.
Reads a 32 bit float.
Reads bytes, blocking until all bytes are read.
(byte buf, int off, int len)
Reads bytes, blocking until all bytes are read.
Reads a 32 bit int.
Deprecated. This method does not properly convert bytes to characters. see DataInputStream for the details and alternatives.
Reads a 64 bit long.
Read an object from the ObjectInputStream.
This method is called by trusted subclasses of ObjectOutputStream that constructed ObjectOutputStream using the protected no-arg constructor.
Reads a 16 bit short.
The readStreamHeader method is provided to allow subclasses to read and verify their own stream headers.
Reads an "unshared" object from the ObjectInputStream.
Reads an unsigned 8 bit byte.
Reads an unsigned 16 bit short.
Reads a UTF format String.
obj, int prio)
Register an object to be validated before the graph is returned.
Load the local class equivalent of the specified stream class description.
This method will allow trusted subclasses of ObjectInputStream to substitute one object for another during deserialization.
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.
Skips bytes, block until all bytes are skipped.
|Methods inherited from class java.io. InputStream|
|mark , markSupported , read , reset , skip|
|Methods inherited from class java.lang. Object|
|clone , equals , finalize , getClass , hashCode , notify , notifyAll , toString , wait , wait , wait|
|Methods inherited from interface java.io. ObjectInput|
|read , skip|
public ObjectInputStream(InputStream in) throws IOException
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.
protected ObjectInputStream() throws IOException, SecurityException
If there is a security manager installed, this method first calls the security manager's checkPermission method with the SerializablePermission("enableSubclassImplementation") permission to ensure it's ok to enable subclassing.
public final Object readObject() throws IOException, ClassNotFoundException
The root object is completly 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.
protected Object readObjectOverride() throws IOException, ClassNotFoundException
public Object readUnshared() throws IOException, ClassNotFoundException
However, for objects which are not enum constants or instances of java.lang.Class and do not define readResolve methods, readUnshared guarantees that the returned object reference is unique and cannot be obtained a second time from the ObjectInputStream that created it, even if the underlying data stream has been manipulated. This guarantee applies only to the base-level object returned by readUnshared, and not to any transitively referenced sub-objects in the returned object graph.
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.
public void defaultReadObject() throws IOException, ClassNotFoundException
public ObjectInputStream.GetField readFields() throws IOException, ClassNotFoundException
public void registerValidation(ObjectInputValidation obj, int prio) throws NotActiveException, InvalidObjectException
protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException
The corresponding method in ObjectOutputStream is annotateClass. 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 a Class object. Once returned, the serialVersionUID of the class is compared to the serialVersionUID of the serialized class. If there is a mismatch, the deserialization fails and an exception is raised.
By default the class name is resolved relative to the class that called readObject.
protected Class resolveProxyClass(String interfaces) throws IOException, ClassNotFoundException
This method is called exactly once for each unique proxy class descriptor in the stream.
The corresponding method in ObjectOutputStream is annotateProxyClass. For a given subclass of ObjectInputStream that overrides this method, the annotateProxyClass method in the corresponding subclass of ObjectOutputStream must write any data or objects read by this method.
The default implementation of this method in ObjectInputStream returns the result of calling Proxy.getProxyClass with the list of Class objects for the interfaces that are named in the interfaces parameter. The Class object for each interface name i is the value returned by calling
Class.forName(i, false, loader)where loader is that of the first non-null class loader up the execution stack, or null if no non-null class loaders are on the stack (the same class loader choice used by the resolveClass method). Unless any of the resolved interfaces are non-public, this same value of loader is also the class loader passed to Proxy.getProxyClass; if non-public interfaces are present, their class loader is passed instead (if more than one non-public interface class loader is encountered, an IllegalAccessError is thrown). If Proxy.getProxyClass throws an IllegalArgumentException, resolveProxyClass will throw a ClassNotFoundException containing the IllegalArgumentException.
protected Object resolveObject(Object obj) throws IOException
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.
protected boolean enableResolveObject(boolean enable) throws SecurityException
If enable is true, and there is a security manager installed, this method first calls the security manager's checkPermission method with the SerializablePermission("enableSubstitution") permission to ensure it's ok to enable the stream to allow objects read from the stream to be replaced.
protected void readStreamHeader() throws IOException, StreamCorruptedException
protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException
public int read() throws IOException
public int read(byte buf, int off, int len) throws IOException
public int available() throws IOException
public void close() throws IOException
public boolean readBoolean() throws IOException
public byte readByte() throws IOException
public int readUnsignedByte() throws IOException
public char readChar() throws IOException
public short readShort() throws IOException
public int readUnsignedShort() throws IOException
public int readInt() throws IOException
public long readLong() throws IOException
public float readFloat() throws IOException
public double readDouble() throws IOException
public void readFully(byte buf) throws IOException
public void readFully(byte buf, int off, int len) throws IOException
public int skipBytes(int len) throws IOException
public String readLine() throws IOException
public String readUTF() throws IOException