⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 objectoutputstream.java

📁 gcc的组建
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* ObjectOutputStream.java -- Class used to write serialized objects   Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005   Free Software Foundation, Inc.This file is part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2, or (at your option)any later version.GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; see the file COPYING.  If not, write to theFree Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA02110-1301 USA.Linking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version. */package java.io;import gnu.java.io.ObjectIdentityWrapper;import gnu.java.lang.reflect.TypeSignature;import gnu.java.security.action.SetAccessibleAction;import java.lang.reflect.Array;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.security.AccessController;import java.util.Hashtable;/** * An <code>ObjectOutputStream</code> can be used to write objects * as well as primitive data in a platform-independent manner to an * <code>OutputStream</code>. * * The data produced by an <code>ObjectOutputStream</code> can be read * and reconstituted by an <code>ObjectInputStream</code>. * * <code>writeObject (Object)</code> is used to write Objects, the * <code>write&lt;type&gt;</code> methods are used to write primitive * data (as in <code>DataOutputStream</code>). Strings can be written * as objects or as primitive data. * * Not all objects can be written out using an * <code>ObjectOutputStream</code>.  Only those objects that are an * instance of <code>java.io.Serializable</code> can be written. * * Using default serialization, information about the class of an * object is written, all of the non-transient, non-static fields of * the object are written, if any of these fields are objects, they are * written out in the same manner. * * An object is only written out the first time it is encountered.  If * the object is encountered later, a reference to it is written to * the underlying stream.  Thus writing circular object graphs * does not present a problem, nor are relationships between objects * in a graph lost. * * Example usage: * <pre> * Hashtable map = new Hashtable (); * map.put ("one", new Integer (1)); * map.put ("two", new Integer (2)); * * ObjectOutputStream oos = * new ObjectOutputStream (new FileOutputStream ("numbers")); * oos.writeObject (map); * oos.close (); * * ObjectInputStream ois = * new ObjectInputStream (new FileInputStream ("numbers")); * Hashtable newmap = (Hashtable)ois.readObject (); * * System.out.println (newmap); * </pre> * * The default serialization can be overriden in two ways. * * By defining a method <code>private void * writeObject (ObjectOutputStream)</code>, a class can dictate exactly * how information about itself is written. * <code>defaultWriteObject ()</code> may be called from this method to * carry out default serialization.  This method is not * responsible for dealing with fields of super-classes or subclasses. * * By implementing <code>java.io.Externalizable</code>.  This gives * the class complete control over the way it is written to the * stream.  If this approach is used the burden of writing superclass * and subclass data is transfered to the class implementing * <code>java.io.Externalizable</code>. * * @see java.io.DataOutputStream * @see java.io.Externalizable * @see java.io.ObjectInputStream * @see java.io.Serializable */public class ObjectOutputStream extends OutputStream  implements ObjectOutput, ObjectStreamConstants{  /**   * Creates a new <code>ObjectOutputStream</code> that will do all of   * its writing onto <code>out</code>.  This method also initializes   * the stream by writing the header information (stream magic number   * and stream version).   *   * @exception IOException Writing stream header to underlying   * stream cannot be completed.   *   * @see #writeStreamHeader()   */  public ObjectOutputStream (OutputStream out) throws IOException  {    realOutput = new DataOutputStream(out);    blockData = new byte[ BUFFER_SIZE ];    blockDataCount = 0;    blockDataOutput = new DataOutputStream(this);    setBlockDataMode(true);    replacementEnabled = false;    isSerializing = false;    nextOID = baseWireHandle;    OIDLookupTable = new Hashtable();    protocolVersion = defaultProtocolVersion;    useSubclassMethod = false;    writeStreamHeader();    if (DEBUG)      {	String val = System.getProperty("gcj.dumpobjects");	if (val != null && !val.equals(""))	  dump = true;      }  }  /**   * Writes a representation of <code>obj</code> to the underlying   * output stream by writing out information about its class, then   * writing out each of the objects non-transient, non-static   * fields.  If any of these fields are other objects,   * they are written out in the same manner.   *   * This method can be overriden by a class by implementing   * <code>private void writeObject (ObjectOutputStream)</code>.   *   * If an exception is thrown from this method, the stream is left in   * an undefined state.   *   * @exception NotSerializableException An attempt was made to   * serialize an <code>Object</code> that is not serializable.   *   * @exception InvalidClassException Somebody tried to serialize   * an object which is wrongly formatted.   *   * @exception IOException Exception from underlying   * <code>OutputStream</code>.   */  public final void writeObject(Object obj) throws IOException  {    if (useSubclassMethod)      {	if (dump)	  dumpElementln ("WRITE OVERRIDE: " + obj);	  	writeObjectOverride(obj);	return;      }    if (dump)      dumpElementln ("WRITE: " + obj);        depth += 2;        boolean was_serializing = isSerializing;    boolean old_mode = setBlockDataMode(false);    try      {	isSerializing = true;	boolean replaceDone = false;	Object replacedObject = null;		while (true)	  {	    if (obj == null)	      {		realOutput.writeByte(TC_NULL);		break;	      }	    Integer handle = findHandle(obj);	    if (handle != null)	      {		realOutput.writeByte(TC_REFERENCE);		realOutput.writeInt(handle.intValue());		break;	      }	    if (obj instanceof Class)	      {		Class cl = (Class)obj;		ObjectStreamClass osc = ObjectStreamClass.lookupForClassObject(cl);		realOutput.writeByte(TC_CLASS);		if (!osc.isProxyClass)		  {		    writeObject (osc);		  }		else		  {		    realOutput.writeByte(TC_PROXYCLASSDESC);		    Class[] intfs = cl.getInterfaces();		    realOutput.writeInt(intfs.length);		    for (int i = 0; i < intfs.length; i++)		      realOutput.writeUTF(intfs[i].getName());		    		    boolean oldmode = setBlockDataMode(true);		    annotateProxyClass(cl);		    setBlockDataMode(oldmode);		    realOutput.writeByte(TC_ENDBLOCKDATA);		    		    writeObject(osc.getSuper());		  }		assignNewHandle(obj);		break;	      }	    if (obj instanceof ObjectStreamClass)	      {		writeClassDescriptor((ObjectStreamClass) obj);		break;	      }	    Class clazz = obj.getClass();	    ObjectStreamClass osc = ObjectStreamClass.lookupForClassObject(clazz);	    if (osc == null)	      throw new NotSerializableException(clazz.getName());	    	    if ((replacementEnabled || obj instanceof Serializable)		&& ! replaceDone)	      {		replacedObject = obj;				if (obj instanceof Serializable)		  {		    try		      {                        Method m = osc.writeReplaceMethod;                        if (m != null)                            obj = m.invoke(obj, new Object[0]);		      }		    catch (IllegalAccessException ignore)		      {		      }		    catch (InvocationTargetException ignore)		      {		      }		  }				if (replacementEnabled)		  obj = replaceObject(obj);				replaceDone = true;		continue;	      }	    if (obj instanceof String)	      {		realOutput.writeByte(TC_STRING);		assignNewHandle(obj);		realOutput.writeUTF((String)obj);		break;	      }	    if (clazz.isArray ())	      {		realOutput.writeByte(TC_ARRAY);		writeObject(osc);		assignNewHandle(obj);		writeArraySizeAndElements(obj, clazz.getComponentType());		break;	      }	    	    realOutput.writeByte(TC_OBJECT);	    writeObject(osc);	    if (replaceDone)	      assignNewHandle(replacedObject);	    else	      assignNewHandle(obj);	    if (obj instanceof Externalizable)	      {		if (protocolVersion == PROTOCOL_VERSION_2)		  setBlockDataMode(true);				((Externalizable)obj).writeExternal(this);				if (protocolVersion == PROTOCOL_VERSION_2)		  {		    setBlockDataMode(false);		    realOutput.writeByte(TC_ENDBLOCKDATA);		  }		break;	      }	    if (obj instanceof Serializable)	      {		Object prevObject = this.currentObject;		ObjectStreamClass prevObjectStreamClass = this.currentObjectStreamClass;		currentObject = obj;		ObjectStreamClass[] hierarchy =		  ObjectStreamClass.getObjectStreamClasses(clazz);				for (int i = 0; i < hierarchy.length; i++)		  {		    currentObjectStreamClass = hierarchy[i];		    		    fieldsAlreadyWritten = false;		    if (currentObjectStreamClass.hasWriteMethod())		      {			if (dump)			  dumpElementln ("WRITE METHOD CALLED FOR: " + obj);			setBlockDataMode(true);			callWriteMethod(obj, currentObjectStreamClass);			setBlockDataMode(false);			realOutput.writeByte(TC_ENDBLOCKDATA);			if (dump)			  dumpElementln ("WRITE ENDBLOCKDATA FOR: " + obj);		      }		    else		      {			if (dump)			  dumpElementln ("WRITE FIELDS CALLED FOR: " + obj);			writeFields(obj, currentObjectStreamClass);		      }		  }		this.currentObject = prevObject;		this.currentObjectStreamClass = prevObjectStreamClass;		currentPutField = null;		break;	      }	    throw new NotSerializableException(clazz.getName()					       + " in "					       + obj.getClass());	  } // end pseudo-loop      }    catch (ObjectStreamException ose)      {	// Rethrow these are fatal.	throw ose;      }    catch (IOException e)      {	realOutput.writeByte(TC_EXCEPTION);	reset(true);	setBlockDataMode(false);	try	  {	    if (DEBUG)	      {		e.printStackTrace(System.out);	      }	    writeObject(e);	  }	catch (IOException ioe)	  {	    StreamCorruptedException ex = 	      new StreamCorruptedException	      (ioe + " thrown while exception was being written to stream.");	    if (DEBUG)	      {		ex.printStackTrace(System.out);	      }	    throw ex;	  }	reset (true);	      }    finally      {	isSerializing = was_serializing;	setBlockDataMode(old_mode);	depth -= 2;	if (dump)	  dumpElementln ("END: " + obj);      }  }  protected void writeClassDescriptor(ObjectStreamClass osc) throws IOException  {    if (osc.isProxyClass)      {        realOutput.writeByte(TC_PROXYCLASSDESC);	Class[] intfs = osc.forClass().getInterfaces();	realOutput.writeInt(intfs.length);	for (int i = 0; i < intfs.length; i++)	  realOutput.writeUTF(intfs[i].getName());        boolean oldmode = setBlockDataMode(true);        annotateProxyClass(osc.forClass());        setBlockDataMode(oldmode);        realOutput.writeByte(TC_ENDBLOCKDATA);      }    else      {        realOutput.writeByte(TC_CLASSDESC);        realOutput.writeUTF(osc.getName());        realOutput.writeLong(osc.getSerialVersionUID());        assignNewHandle(osc);        int flags = osc.getFlags();        if (protocolVersion == PROTOCOL_VERSION_2	    && osc.isExternalizable())        flags |= SC_BLOCK_DATA;        realOutput.writeByte(flags);        ObjectStreamField[] fields = osc.fields;        realOutput.writeShort(fields.length);        ObjectStreamField field;        for (int i = 0; i < fields.length; i++)          {	    field = fields[i];	    realOutput.writeByte(field.getTypeCode ());	    realOutput.writeUTF(field.getName ());	    if (! field.isPrimitive())	      writeObject(field.getTypeString());          }        boolean oldmode = setBlockDataMode(true);        annotateClass(osc.forClass());        setBlockDataMode(oldmode);        realOutput.writeByte(TC_ENDBLOCKDATA);      }    if (osc.isSerializable() || osc.isExternalizable())      writeObject(osc.getSuper());    else      writeObject(null);  }    /**   * Writes the current objects non-transient, non-static fields from   * the current class to the underlying output stream.   *   * This method is intended to be called from within a object's   * <code>private void writeObject (ObjectOutputStream)</code>   * method.   *   * @exception NotActiveException This method was called from a   * context other than from the current object's and current class's   * <code>private void writeObject (ObjectOutputStream)</code>   * method.   *   * @exception IOException Exception from underlying   * <code>OutputStream</code>.   */  public void defaultWriteObject()    throws IOException, NotActiveException  {    markFieldsWritten();    writeFields(currentObject, currentObjectStreamClass);  }  private void markFieldsWritten() throws IOException  {    if (currentObject == null || currentObjectStreamClass == null)      throw new NotActiveException	("defaultWriteObject called by non-active class and/or object");    if (fieldsAlreadyWritten)      throw new IOException	("Only one of writeFields and defaultWriteObject may be called, and it may only be called once");    fieldsAlreadyWritten = true;  }  /**   * Resets stream to state equivalent to the state just after it was   * constructed.   *   * Causes all objects previously written to the stream to be   * forgotten.  A notification of this reset is also written to the   * underlying stream.   *   * @exception IOException Exception from underlying   * <code>OutputStream</code> or reset called while serialization is   * in progress.   */  public void reset() throws IOException  {    reset(false);  }  private void reset(boolean internal) throws IOException  {    if (!internal)      {	if (isSerializing)	  throw new IOException("Reset called while serialization in progress");

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -