objectinputstream.java
来自「This is a resource based on j2me embedde」· Java 代码 · 共 1,784 行 · 第 1/5 页
JAVA
1,784 行
/* * @(#)ObjectInputStream.java 1.123 06/10/10 * * Copyright 1990-2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. * */package java.io;import java.lang.reflect.Array;import java.lang.reflect.Modifier;import java.lang.reflect.Proxy;import java.security.AccessController;import java.security.PrivilegedAction;import java.util.Arrays;import java.util.HashMap;import sun.misc.SoftCache;import sun.misc.CVM;/* Back-ported JDK 1.4 implementation *//** * An ObjectInputStream deserializes primitive data and objects previously * written using an ObjectOutputStream. * * <p>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.<p> * * 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. <p> * * Only objects that support the java.io.Serializable or * java.io.Externalizable interface can be read from streams. * * <p>The method <STRONG>readObject</STRONG> 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.<p> * * Primitive data types can be read from the stream using the appropriate * method on DataInput. <p> * * 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. * * <p>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. * * <p>For example to read from a stream as written by the example in * ObjectOutputStream: * <br> * <pre> * 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(); * </pre> * * <p>Classes control how they are serialized by implementing either the * java.io.Serializable or java.io.Externalizable interfaces.<P> * * 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. * * <p>Serializable classes that require special handling during the * serialization and deserialization process should implement the following * methods:<p> * * <PRE> * private void writeObject(java.io.ObjectOutputStream stream) * throws IOException; * private void readObject(java.io.ObjectInputStream stream) * throws IOException, ClassNotFoundException; * private void readObjectNoData() * throws ObjectStreamException; * </PRE><p> * * 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. * * <p>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. * * <p>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 * <code>ObjectStreamConstants.PROTOCOL_VERSION_1</code> protocol, in which the * end of data written by writeExternal methods is not demarcated, and hence * cannot be detected. * * <p>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. * * <p>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. * * <p>Any exception that occurs while deserializing an object will be * caught by the ObjectInputStream and abort the reading process. * * <p>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. * * @version 1.135, 01/09/15 * @see java.io.DataInput * @see java.io.ObjectOutputStream * @see java.io.Serializable * @see <a href="../../../guide/serialization/spec/input.doc.html"> Object Serialization Specification, Section 3, Object Input Classes</a> * @since JDK1.1 */public class ObjectInputStream extends InputStream implements ObjectInput, ObjectStreamConstants{ /** handle value representing null */ private static final int NULL_HANDLE = -1; /** marker for unshared objects in internal handle table */ private static final Object unsharedMarker = new Object(); /** table mapping primitive type names to corresponding class objects */ private static final HashMap primClasses = new HashMap(8, 1.0F); static { primClasses.put("boolean", boolean.class); primClasses.put("byte", byte.class); primClasses.put("char", char.class); primClasses.put("short", short.class); primClasses.put("int", int.class); primClasses.put("long", long.class); primClasses.put("float", float.class); primClasses.put("double", double.class); } /** cache of subclass security audit results */ // - Back-ported from JDK 1.4 private static final SoftCache subclassAudits = new SoftCache(5); /** filter stream for handling block data conversion */ private final BlockDataInputStream bin; /** validation callback list */ private final ValidationList vlist; /** recursion depth */ private int depth; /** whether stream is closed */ private boolean closed; /** wire handle -> obj/exception map */ private final HandleTable handles; /** scratch field for passing handle values up/down call stack */ private int passHandle = NULL_HANDLE; /** flag set when at end of field value block with no TC_ENDBLOCKDATA */ private boolean defaultDataEnd = false; /** buffer for reading primitive field values */ private byte[] primVals; /** if true, invoke readObjectOverride() instead of readObject() */ private final boolean enableOverride; /** if true, invoke resolveObject() */ private boolean enableResolve; // values below valid only during upcalls to readObject()/readExternal() /** object currently being deserialized */ private Object curObj; /** descriptor for current class (null if in readExternal()) */ private ObjectStreamClass curDesc; /** current GetField object */ private GetFieldImpl curGet; /** * Creates 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. * * <p>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. * * @param in input stream to read from * @throws StreamCorruptedException if the stream header is incorrect * @throws IOException if an I/O error occurs while reading stream header * @throws SecurityException if untrusted subclass illegally overrides * security-sensitive methods * @throws NullPointerException if <code>in</code> is <code>null</code> * @see ObjectInputStream#ObjectInputStream() * @see ObjectInputStream#readFields() * @see ObjectOutputStream#ObjectOutputStream(OutputStream). */ public ObjectInputStream(InputStream in) throws IOException { verifySubclass(); bin = new BlockDataInputStream(in); handles = new HandleTable(10); vlist = new ValidationList(); enableOverride = false; readStreamHeader(); bin.setBlockDataMode(true); } /** * Provide a way for subclasses that are completely reimplementing * ObjectInputStream to not have to allocate private data just used by * this implementation of ObjectInputStream. * * <p>If there is a security manager installed, this method first calls the * security manager's <code>checkPermission</code> method with the * <code>SerializablePermission("enableSubclassImplementation")</code> * permission to ensure it's ok to enable subclassing. * * @exception IOException Thrown if not called by a subclass. * @throws SecurityException * if a security manager exists and its * <code>checkPermission</code> method denies * enabling subclassing. * * @see SecurityManager#checkPermission * @see java.io.SerializablePermission */ protected ObjectInputStream() throws IOException, SecurityException { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(ObjectStreamConstants.SUBCLASS_IMPLEMENTATION_PERMISSION); } bin = null; handles = null; vlist = null; enableOverride = true; } /** * Read 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. <p> * * 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. * * @exception java.lang.ClassNotFoundException Class of a serialized object * cannot be found. * @exception InvalidClassException Something is wrong with a class used by * serialization. * @exception StreamCorruptedException Control information in the * stream is inconsistent. * @exception OptionalDataException Primitive data was found in the * stream instead of objects. * @exception IOException Any of the usual Input/Output related exceptions. */ public final Object readObject() throws OptionalDataException, ClassNotFoundException, IOException { if (enableOverride) { return readObjectOverride(); } // if nested read, passHandle contains handle of enclosing object int outerHandle = passHandle; try { Object obj = readObject0(false); handles.markDependency(outerHandle, passHandle);
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?