Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Is it not possible to append to an ObjectOutputStream? I am trying to append to a list of objects. Following snippet is a function that is called whenever a job is finished. FileOutputStream fos = new FileOutputStream (preferences.getAppDataLocation() + "history" , true); ObjectOutputStream out = new ObjectOutputStream(fos); out.writeObject( new Stuff(stuff) ); out.close(); But ...
The following code is causing Java heap space out of memory for some 3 million rows. Memory allocated to JVM is 4 GB, using 64 bit installation. while (rs.next()) { ArrayList<String> arrayList = new ArrayList<String>(); for (int i = 1; i <= columnCount; i++) { arrayList.add(rs.getString(i)); } objOS.writeObject(arrayList); } Question is that the ...
I'm working on a Java server that handles a LOT of very dense traffic. The server accepts packets from clients (often many megabytes) and forwards them to other clients. The server never explicitly stores any of the incoming/outgoing packets. Yet the server continually runs into OutOfMemoryException exceptions. I added System.gc() into the message passing component of the server, hoping that m...
Sometimes (quite a lot, actually) we get a situation in Java where two objects are pointing to the same thing. Now if we serialise these separately it is quite appropriate that the serialised forms have separate copies of the object as it should be possible to open one without the other. However if we now deserialise them both, we find that they are still separated. Is there any way to link the...
Why does ObjectOutputStream.writeObject() not take a Serializable? Why is it taking an Object?
I'm getting these messages: [#|2010-07-30T11:28:32.723+0000|WARNING|glassfish3.0.1|javax.faces|_ThreadID=37;_ThreadName=Thread-1;|Setting non-serializable attribute value into ViewMap: (key: MyBackingBean, value class: foo.bar.org.jsf.MyBackingBean)|#] Do these mean that my JSF backing beans should implement Serializable? Or are they refering to some other problem?
I have hashtable, my program want to record the valuse of hashtable to process later! But i have a quesiton . Can web write oject hastable in to file ? if can,how to load that file ?
Just want to know if there's a tutorial or an how-to for serializing object, put it in a stream over network, and deserialize it on the other point. I understand the principles of serialization, I/O, streams, sockets and so on, just want an example (client sending object to a server) to start with. Thank you.
I have two lists (list1 and list2) containing references to some objects, where some of the list entries may point to the same object. Then, for various reasons, I am serializing these lists to two separate files. Finally, when I deserialize the lists, I would like to ensure that I am not re-creating more objects than needed. In other words, it should still be possible for some entry of List1 t...
I am reading the chapter on Serialization in Effective Java. Who calls the readObject() and writeObject()? Why are these methods declared private ? The below is a piece of code from the book // StringList with a reasonable custom serialized form public final class StringList implements Serializable { private transient int size = 0; private transient Entry head = null; //Other co...
We have this use case where we would like to compress and store objects (in-memory) and decompress them as and when required. The data we want to compress is quite varied, from float vectors to strings to dates. Can someone suggest any good compression technique to do this ? We are looking at ease of compression and speed of decompression as the most important factors. Thanks.
does serialization in Java always have to shrink the memory that is used to hold an object structure? Or is it likely that serialization will have higher costs? In other words: Is serialization a tool to shrink the memory footprint of object structures in Java? Edit I'm totally aware of what serialization was intended for, but thanks anyway :-) But you know, tools can be misused. My questio...
What are the lightweight options one has to persist Java objects ? I'm looking for the easiest possible solution. I don't want anything fancy featurewise just something simple that works with reasonnably simple objects (some collections, relationships and simple inheritance) and doesn't bring too much apparent complexity (if any) to the existing codebase. The options I'm aware of include Hib...
I have an ArrayList of custom, simple Serializable objects I would like to cache to disk and read on re-launch. My data is very small, about 25 objects and at most 5 lists so I think SQLite would be overkill. In the iPhone world I would use NSKeyedArchiver and NSKeyedUnarchiver which works great. On Android I've attempted to do this with with a FileOutputStream and ObjectOutputStream and whi...
The block quotes are from the Java Docs - A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality. A DataInputStream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. The DataInputStre...
Is it possible to write objects in Java to a binary file? The objects I want to write would be 2 arrays of String objects. The reason I want to do this is to save persistent data. If there is some easier way to do this let me know. Thanks in advance!
I have the following code: ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("test.dat")); ArrayList<String> list = null; for(int i = 0; i < 10; i++) { list = new ArrayList<String>(); list.add("Object" + i); oo.writeObject(list); } oo.close(); When I open the test.dat file and unserialize the objects, I get all the objects. But if I change my code...
I have a client-server application where the server sends all clients a list of all clients every time a new client socket joins. The problem is, that when a new client joins it gets the right list but the old clients get the old list they got when joining themselves. Sort of like they take the same object from the input stream every time. Can I somehow flush the input stream? Reading the obj...
I have two web applications say App1 and App2. I want to call a servlet which is in App2 from a servlet in App1. I'm using URLConnection for this. I'm able to pass parameters to the servlet in App2 also and I'm also able to receive response from the servlet as string. But I want to send java objects from the servlet in App2 and receive them in servlet of App1. How to achieve this?
If I inherit from a class that is serializable but I specifically do not want my class to be serializable; what's the best way to strictly prevent serialization? If there was a method in java.io.Serializable maybe I could throw an exception, but Serializable is empty.
I have an ArrayList that i want to send through UDP but the send method requires byte[]. Can anyone tell me how to convert my ArrayList to byte[]? Thank you!
   /*
    * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code 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.  Sun designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Sun in the LICENSE file that accompanied this code.
   *
   * This code 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 in the LICENSE file that
   * accompanied this code).
   *
   * 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 USA or visit www.sun.com if you need additional information or
   * have any questions.
   */
  
  package java.io;
  
  import java.util.Arrays;
  import java.util.List;
  import static java.io.ObjectStreamClass.processQueue;

An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconstituted on another host or in another process.

Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.

The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.

Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using the writeUTF method.

The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.

For example to write an object that can be read by the example in ObjectInputStream:

      FileOutputStream fos = new FileOutputStream("t.tmp");
      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeInt(12345);
      oos.writeObject("Today");
      oos.writeObject(new Date());

      oos.close();
 

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

 private void readObject(java.io.ObjectInputStream stream)
     throws IOException, ClassNotFoundException;
 private void writeObject(java.io.ObjectOutputStream stream)
     throws IOException
 private void readObjectNoData()
     throws ObjectStreamException;
 

The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object's superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

Serialization does not write out 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.

Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization 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 serialized 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 serialize an enum constant, ObjectOutputStream writes the string returned by the constant's name method. 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 serialized cannot be customized; any class-specific writeObject and writeReplace methods defined by enum types are ignored during serialization. Similarly, any serialPersistentFields or serialVersionUID field declarations are also ignored--all enum types have a fixed serialVersionUID of 0L.

Primitive data, excluding serializable fields and externalizable data, is written to the ObjectOutputStream in block-data records. A block data record is composed of a header and data. The block data header consists of a marker and the number of bytes to follow the header. Consecutive primitive data writes are merged into one block-data record. The blocking factor used for a block-data record will be 1024 bytes. Each block-data record will be filled up to 1024 bytes, or be written whenever there is a termination of block-data mode. Calls to the ObjectOutputStream methods writeObject, defaultWriteObject and writeFields initially terminate any existing block-data record.

Author(s):
Mike Warres
Roger Riggs
Since:
JDK1.1
See also:
DataOutput
ObjectInputStream
Serializable
Externalizable
Object Serialization Specification, Section 2, Object Output Classes
 
 public class ObjectOutputStream
     extends OutputStream implements ObjectOutputObjectStreamConstants
 {
 
     private static class Caches {
        
cache of subclass security audit results
 
         static final ConcurrentMap<WeakClassKey,BooleansubclassAudits =
             new ConcurrentHashMap<WeakClassKey,Boolean>();

        
queue for WeakReferences to audited subclasses
 
         static final ReferenceQueue<Class<?>> subclassAuditsQueue =
             new ReferenceQueue<Class<?>>();
     }

    
filter stream for handling block data conversion
 
     private final BlockDataOutputStream bout;
    
obj -> wire handle map
 
     private final HandleTable handles;
    
obj -> replacement obj map
 
     private final ReplaceTable subs;
    
stream protocol version
 
     private int protocol = ;
    
recursion depth
 
     private int depth;

    
buffer for writing primitive field values
 
     private byte[] primVals;

    
if true, invoke writeObjectOverride() instead of writeObject()
 
     private final boolean enableOverride;
    
if true, invoke replaceObject()
 
     private boolean enableReplace;
 
     // values below valid only during upcalls to writeObject()/writeExternal()
     
object currently being serialized
 
     private Object curObj;
    
descriptor for current class (null if in writeExternal())
 
     private ObjectStreamClass curDesc;
    
current PutField object
 
     private PutFieldImpl curPut;

    
custom storage for debug trace info
 
     private final DebugTraceInfoStack debugInfoStack;

    
value of "sun.io.serialization.extendedDebugInfo" property, as true or false for extended information about exception's place
 
     private static final boolean extendedDebugInfo =
         java.security.AccessController.doPrivileged(
             new sun.security.action.GetBooleanAction(
                 "sun.io.serialization.extendedDebugInfo")).booleanValue();

    
Creates an ObjectOutputStream that writes to the specified OutputStream. This constructor writes the serialization stream header to the underlying stream; callers may wish to flush the stream immediately to ensure that constructors for receiving ObjectInputStreams will not block when reading 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 ObjectOutputStream.putFields or ObjectOutputStream.writeUnshared methods.

Parameters:
out output stream to write to
Throws:
IOException if an I/O error occurs while writing stream header
java.lang.SecurityException if untrusted subclass illegally overrides security-sensitive methods
java.lang.NullPointerException if out is null
Since:
1.4
See also:
ObjectOutputStream.ObjectOutputStream()
putFields()
ObjectInputStream.ObjectInputStream.(java.io.InputStream)
 
     public ObjectOutputStream(OutputStream outthrows IOException {
         verifySubclass();
          = new BlockDataOutputStream(out);
          = new HandleTable(10, (float) 3.00);
          = new ReplaceTable(10, (float) 3.00);
          = false;
         writeStreamHeader();
         .setBlockDataMode(true);
         if () {
              = new DebugTraceInfoStack();
         } else {
              = null;
         }
     }

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

If there is a security manager installed, this method first calls the security manager's checkPermission method with a SerializablePermission("enableSubclassImplementation") permission to ensure it's ok to enable subclassing.

Throws:
java.lang.SecurityException if a security manager exists and its checkPermission method denies enabling subclassing.
See also:
java.lang.SecurityManager.checkPermission(java.security.Permission)
SerializablePermission
 
     protected ObjectOutputStream() throws IOExceptionSecurityException {
         SecurityManager sm = System.getSecurityManager();
         if (sm != null) {
         }
          = null;
          = null;
          = null;
          = true;
          = null;
     }

    
Specify stream protocol version to use when writing the stream.

This routine provides a hook to enable the current version of Serialization to write in a format that is backwards compatible to a previous version of the stream format.

Every effort will be made to avoid introducing additional backwards incompatibilities; however, sometimes there is no other alternative.

Parameters:
version use ProtocolVersion from java.io.ObjectStreamConstants.
Throws:
java.lang.IllegalStateException if called after any objects have been serialized.
java.lang.IllegalArgumentException if invalid version is passed in.
IOException if I/O errors occur
Since:
1.2
See also:
ObjectStreamConstants.PROTOCOL_VERSION_1
ObjectStreamConstants.PROTOCOL_VERSION_2
 
     public void useProtocolVersion(int versionthrows IOException {
         if (.size() != 0) {
             // REMIND: implement better check for pristine stream?
             throw new IllegalStateException("stream non-empty");
         }
         switch (version) {
             case :
             case :
                  = version;
                 break;
 
             default:
                 throw new IllegalArgumentException(
                     "unknown version: " + version);
         }
     }

    
Write the specified object to the ObjectOutputStream. 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 written. Default serialization for a class can be overridden using the writeObject and the readObject methods. Objects referenced by this object are written transitively so that a complete equivalent graph of objects can be reconstructed by an ObjectInputStream.

Exceptions are thrown for problems with the OutputStream and for classes that should not be serialized. All exceptions are fatal to the OutputStream, which is left in an indeterminate state, and it is up to the caller to ignore or recover the stream state.

Throws:
InvalidClassException Something is wrong with a class used by serialization.
NotSerializableException Some object to be serialized does not implement the java.io.Serializable interface.
IOException Any exception thrown by the underlying OutputStream.
 
     public final void writeObject(Object objthrows IOException {
         if () {
             writeObjectOverride(obj);
             return;
         }
         try {
             writeObject0(objfalse);
         } catch (IOException ex) {
             if ( == 0) {
                 writeFatalException(ex);
             }
             throw ex;
         }
     }

    
Method used by subclasses to override the default writeObject method. This method is called by trusted subclasses of ObjectInputStream that constructed ObjectInputStream using the protected no-arg constructor. The subclass is expected to provide an override method with the modifier "final".

Parameters:
obj object to be written to the underlying stream
Throws:
IOException if there are I/O errors while writing to the underlying stream
Since:
1.2
See also:
ObjectOutputStream()
writeObject(java.lang.Object)
 
     protected void writeObjectOverride(Object objthrows IOException {
     }

    
Writes an "unshared" object to the ObjectOutputStream. This method is identical to writeObject, except that it always writes the given object as a new, unique object in the stream (as opposed to a back-reference pointing to a previously serialized instance). Specifically:
  • An object written via writeUnshared is always serialized in the same manner as a newly appearing object (an object that has not been written to the stream yet), regardless of whether or not the object has been written previously.
  • If writeObject is used to write an object that has been previously written with writeUnshared, the previous writeUnshared operation is treated as if it were a write of a separate object. In other words, ObjectOutputStream will never generate back-references to object data written by calls to writeUnshared.
While writing an object via writeUnshared does not in itself guarantee a unique reference to the object when it is deserialized, it allows a single object to be defined multiple times in a stream, so that multiple calls to readUnshared by the receiver will not conflict. Note that the rules described above only apply to the base-level object written with writeUnshared, and not to any transitively referenced sub-objects in the object graph to be serialized.

ObjectOutputStream 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.

Parameters:
obj object to write to stream
Throws:
NotSerializableException if an object in the graph to be serialized does not implement the Serializable interface
InvalidClassException if a problem exists with the class of an object to be serialized
IOException if an I/O error occurs during serialization
Since:
1.4
 
     public void writeUnshared(Object objthrows IOException {
         try {
             writeObject0(objtrue);
         } catch (IOException ex) {
             if ( == 0) {
                 writeFatalException(ex);
             }
             throw ex;
         }
     }

    
Write the non-static and non-transient fields of the current class to this stream. This may only be called from the writeObject method of the class being serialized. It will throw the NotActiveException if it is called otherwise.

Throws:
IOException if I/O errors occur while writing to the underlying OutputStream
 
     public void defaultWriteObject() throws IOException {
         if ( == null ||  == null) {
             throw new NotActiveException("not in call to writeObject");
         }
         .setBlockDataMode(false);
         defaultWriteFields();
         .setBlockDataMode(true);
     }

    
Retrieve the object used to buffer persistent fields to be written to the stream. The fields will be written to the stream when writeFields method is called.

Returns:
an instance of the class Putfield that holds the serializable fields
Throws:
IOException if I/O errors occur
Since:
1.2
 
     public ObjectOutputStream.PutField putFields() throws IOException {
         if ( == null) {
             if ( == null ||  == null) {
                 throw new NotActiveException("not in call to writeObject");
             }
              = new PutFieldImpl();
         }
         return ;
     }

    
Write the buffered fields to the stream.

Throws:
IOException if I/O errors occur while writing to the underlying stream
NotActiveException Called when a classes writeObject method was not called to write the state of the object.
Since:
1.2
 
     public void writeFields() throws IOException {
         if ( == null) {
             throw new NotActiveException("no current PutField object");
         }
         .setBlockDataMode(false);
         .writeFields();
         .setBlockDataMode(true);
     }

    
Reset will disregard the state of any objects already written to the stream. The state is reset to be the same as a new ObjectOutputStream. The current point in the stream is marked as reset so the corresponding ObjectInputStream will be reset at the same point. Objects previously written to the stream will not be refered to as already being in the stream. They will be written to the stream again.

Throws:
IOException if reset() is invoked while serializing an object.
 
     public void reset() throws IOException {
         if ( != 0) {
             throw new IOException("stream active");
         }
         .setBlockDataMode(false);
         .writeByte();
         clear();
         .setBlockDataMode(true);
     }

    
Subclasses may implement this method to allow class data to be stored in the stream. By default this method does nothing. The corresponding method in ObjectInputStream is resolveClass. This method is called exactly once for each unique class in the stream. The class name and signature will have already been written to the stream. This method may make free use of the ObjectOutputStream to save any representation of the class it deems suitable (for example, the bytes of the class file). The resolveClass method in the corresponding subclass of ObjectInputStream must read and use any data or objects written by annotateClass.

Parameters:
cl the class to annotate custom data for
Throws:
IOException Any exception thrown by the underlying OutputStream.
 
     protected void annotateClass(Class<?> clthrows IOException {
     }

    
Subclasses may implement this method to store custom data in the stream along with descriptors for dynamic proxy classes.

This method is called exactly once for each unique proxy class descriptor in the stream. The default implementation of this method in ObjectOutputStream does nothing.

The corresponding method in ObjectInputStream is resolveProxyClass. For a given subclass of ObjectOutputStream that overrides this method, the resolveProxyClass method in the corresponding subclass of ObjectInputStream must read any data or objects written by annotateProxyClass.

Parameters:
cl the proxy class to annotate custom data for
Throws:
IOException any exception thrown by the underlying OutputStream
Since:
1.3
See also:
ObjectInputStream.resolveProxyClass(java.lang.String[])
 
     protected void annotateProxyClass(Class<?> clthrows IOException {
     }

    
This method will allow trusted subclasses of ObjectOutputStream to substitute one object for another during serialization. Replacing objects is disabled until enableReplaceObject is called. The enableReplaceObject method checks that the stream requesting to do replacement can be trusted. The first occurrence of each object written into the serialization stream is passed to replaceObject. Subsequent references to the object are replaced by the object returned by the original call to replaceObject. To ensure that the private state of objects is not unintentionally exposed, only trusted streams may use replaceObject.

The ObjectOutputStream.writeObject method takes a parameter of type Object (as opposed to type Serializable) to allow for cases where non-serializable objects are replaced by serializable ones.

When a subclass is replacing objects it must insure that either a complementary substitution must be made during deserialization or 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. This method should return the object to be substituted or the original object.

Null can be returned as the object to be substituted, but may cause NullReferenceException in classes that contain references to the original object since they may be expecting an object instead of null.

Parameters:
obj the object to be replaced
Returns:
the alternate object that replaced the specified one
Throws:
IOException Any exception thrown by the underlying OutputStream.
 
     protected Object replaceObject(Object objthrows IOException {
         return obj;
     }

    
Enable the stream to do replacement of objects in the stream. When enabled, the replaceObject method is called for every object being serialized.

If enable is true, and there is a security manager installed, this method first calls the security manager's checkPermission method with a SerializablePermission("enableSubstitution") permission to ensure it's ok to enable the stream to do replacement of objects in the stream.

Parameters:
enable boolean parameter to enable replacement of objects
Returns:
the previous setting before this method was invoked
Throws:
java.lang.SecurityException if a security manager exists and its checkPermission method denies enabling the stream to do replacement of objects in the stream.
See also:
java.lang.SecurityManager.checkPermission(java.security.Permission)
SerializablePermission
 
     protected boolean enableReplaceObject(boolean enable)
         throws SecurityException
     {
         if (enable == ) {
             return enable;
         }
         if (enable) {
             SecurityManager sm = System.getSecurityManager();
             if (sm != null) {
                 sm.checkPermission();
             }
         }
          = enable;
         return !;
     }

    
The writeStreamHeader method is provided so subclasses can append or prepend their own header to the stream. It writes the magic number and version to the stream.

Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     protected void writeStreamHeader() throws IOException {
         .writeShort();
         .writeShort();
     }

    
Write the specified class descriptor to the ObjectOutputStream. Class descriptors are used to identify the classes of objects written to the stream. Subclasses of ObjectOutputStream may override this method to customize the way in which class descriptors are written to the serialization stream. The corresponding method in ObjectInputStream, readClassDescriptor, should then be overridden to reconstitute the class descriptor from its custom stream representation. By default, this method writes class descriptors according to the format defined in the Object Serialization specification.

Note that this method will only be called if the ObjectOutputStream is not using the old serialization stream format (set by calling ObjectOutputStream's useProtocolVersion method). If this serialization stream is using the old format (PROTOCOL_VERSION_1), the class descriptor will be written internally in a manner that cannot be overridden or customized.

Parameters:
desc class descriptor to write to the stream
Throws:
IOException If an I/O error has occurred.
Since:
1.3
See also:
ObjectInputStream.readClassDescriptor()
useProtocolVersion(int)
ObjectStreamConstants.PROTOCOL_VERSION_1
 
     protected void writeClassDescriptor(ObjectStreamClass desc)
         throws IOException
     {
         desc.writeNonProxy(this);
     }

    
Writes a byte. This method will block until the byte is actually written.

Parameters:
val the byte to be written to the stream
Throws:
IOException If an I/O error has occurred.
 
     public void write(int valthrows IOException {
         .write(val);
     }

    
Writes an array of bytes. This method will block until the bytes are actually written.

Parameters:
buf the data to be written
Throws:
IOException If an I/O error has occurred.
 
     public void write(byte[] bufthrows IOException {
         .write(buf, 0, buf.lengthfalse);
     }

    
Writes a sub array of bytes.

Parameters:
buf the data to be written
off the start offset in the data
len the number of bytes that are written
Throws:
IOException If an I/O error has occurred.
 
     public void write(byte[] bufint offint lenthrows IOException {
         if (buf == null) {
             throw new NullPointerException();
         }
         int endoff = off + len;
         if (off < 0 || len < 0 || endoff > buf.length || endoff < 0) {
             throw new IndexOutOfBoundsException();
         }
         .write(bufofflenfalse);
     }

    
Flushes the stream. This will write any buffered output bytes and flush through to the underlying stream.

Throws:
IOException If an I/O error has occurred.
 
     public void flush() throws IOException {
         .flush();
     }

    
Drain any buffered data in ObjectOutputStream. Similar to flush but does not propagate the flush to the underlying stream.

Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     protected void drain() throws IOException {
         .drain();
     }

    
Closes the stream. This method must be called to release any resources associated with the stream.

Throws:
IOException If an I/O error has occurred.
 
     public void close() throws IOException {
         flush();
         clear();
         .close();
     }

    
Writes a boolean.

Parameters:
val the boolean to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeBoolean(boolean valthrows IOException {
         .writeBoolean(val);
     }

    
Writes an 8 bit byte.

Parameters:
val the byte value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeByte(int valthrows IOException  {
         .writeByte(val);
     }

    
Writes a 16 bit short.

Parameters:
val the short value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeShort(int val)  throws IOException {
         .writeShort(val);
     }

    
Writes a 16 bit char.

Parameters:
val the char value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeChar(int val)  throws IOException {
         .writeChar(val);
     }

    
Writes a 32 bit int.

Parameters:
val the integer value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeInt(int val)  throws IOException {
         .writeInt(val);
     }

    
Writes a 64 bit long.

Parameters:
val the long value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeLong(long val)  throws IOException {
         .writeLong(val);
     }

    
Writes a 32 bit float.

Parameters:
val the float value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeFloat(float valthrows IOException {
         .writeFloat(val);
     }

    
Writes a 64 bit double.

Parameters:
val the double value to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeDouble(double valthrows IOException {
         .writeDouble(val);
     }

    
Writes a String as a sequence of bytes.

Parameters:
str the String of bytes to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeBytes(String strthrows IOException {
         .writeBytes(str);
     }

    
Writes a String as a sequence of chars.

Parameters:
str the String of chars to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeChars(String strthrows IOException {
         .writeChars(str);
     }

    
Primitive data write of this String in modified UTF-8 format. Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream.

Parameters:
str the String to be written
Throws:
IOException if I/O errors occur while writing to the underlying stream
 
     public void writeUTF(String strthrows IOException {
         .writeUTF(str);
     }

    
Provide programmatic access to the persistent fields to be written to ObjectOutput.

Since:
1.2
 
     public static abstract class PutField {

        
Put the value of the named boolean field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not boolean
 
         public abstract void put(String nameboolean val);

        
Put the value of the named byte field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not byte
 
         public abstract void put(String namebyte val);

        
Put the value of the named char field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not char
 
         public abstract void put(String namechar val);

        
Put the value of the named short field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not short
 
         public abstract void put(String nameshort val);

        
Put the value of the named int field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not int
 
         public abstract void put(String nameint val);

        
Put the value of the named long field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not long
 
         public abstract void put(String namelong val);

        
Put the value of the named float field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not float
 
         public abstract void put(String namefloat val);

        
Put the value of the named double field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not double
 
         public abstract void put(String namedouble val);

        
Put the value of the named Object field into the persistent field.

Parameters:
name the name of the serializable field
val the value to assign to the field (which may be null)
Throws:
java.lang.IllegalArgumentException if name does not match the name of a serializable field for the class whose fields are being written, or if the type of the named field is not a reference type
 
         public abstract void put(String nameObject val);

        
Write the data and fields to the specified ObjectOutput stream, which must be the same stream that produced this PutField object.

Deprecated:
This method does not write the values contained by this PutField object in a proper format, and may result in corruption of the serialization stream. The correct way to write PutField data is by calling the ObjectOutputStream.writeFields() method.
Parameters:
out the stream to write the data and fields to
Throws:
IOException if I/O errors occur while writing to the underlying stream
java.lang.IllegalArgumentException if the specified stream is not the same stream that produced this PutField object
 
         @Deprecated
         public abstract void write(ObjectOutput outthrows IOException;
     }


    
Returns protocol version in use.
    int getProtocolVersion() {
        return ;
    }

    
Writes string without allowing it to be replaced in stream. Used by ObjectStreamClass to write class descriptor type strings.
    void writeTypeString(String strthrows IOException {
        int handle;
        if (str == null) {
            writeNull();
        } else if ((handle = .lookup(str)) != -1) {
            writeHandle(handle);
        } else {
            writeString(strfalse);
        }
    }

    
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.
    private void verifySubclass() {
        Class cl = getClass();
        if (cl == ObjectOutputStream.class) {
            return;
        }
        SecurityManager sm = System.getSecurityManager();
        if (sm == null) {
            return;
        }
        WeakClassKey key = new WeakClassKey(cl.);
        Boolean result = ..get(key);
        if (result == null) {
            result = Boolean.valueOf(auditSubclass(cl));
            ..putIfAbsent(keyresult);
        }
        if (result.booleanValue()) {
            return;
        }
    }

    
Performs reflective checks on given subclass to verify that it doesn't override security-sensitive non-final methods. Returns true if subclass is "safe", false otherwise.
    private static boolean auditSubclass(final Class subcl) {
        Boolean result = AccessController.doPrivileged(
            new PrivilegedAction<Boolean>() {
                public Boolean run() {
                    for (Class cl = subcl;
                         cl != ObjectOutputStream.class;
                         cl = cl.getSuperclass())
                    {
                        try {
                            cl.getDeclaredMethod(
                                "writeUnshared"new Class[] { Object.class });
                            return .;
                        } catch (NoSuchMethodException ex) {
                        }
                        try {
                            cl.getDeclaredMethod("putFields", (Class[]) null);
                            return .;
                        } catch (NoSuchMethodException ex) {
                        }
                    }
                    return .;
                }
            }
        );
        return result.booleanValue();
    }

    
Clears internal data structures.
    private void clear() {
        .clear();
        .clear();
    }

    
Underlying writeObject/writeUnshared implementation.
    private void writeObject0(Object objboolean unshared)
        throws IOException
    {
        boolean oldMode = .setBlockDataMode(false);
        ++;
        try {
            // handle previously written and non-replaceable objects
            int h;
            if ((obj = .lookup(obj)) == null) {
                writeNull();
                return;
            } else if (!unshared && (h = .lookup(obj)) != -1) {
                writeHandle(h);
                return;
            } else if (obj instanceof Class) {
                writeClass((Classobjunshared);
                return;
            } else if (obj instanceof ObjectStreamClass) {
                writeClassDesc((ObjectStreamClassobjunshared);
                return;
            }
            // check for replacement object
            Object orig = obj;
            Class cl = obj.getClass();
            ObjectStreamClass desc;
            for (;;) {
                // REMIND: skip this check for strings/arrays?
                Class repCl;
                desc = ObjectStreamClass.lookup(cltrue);
                if (!desc.hasWriteReplaceMethod() ||
                    (obj = desc.invokeWriteReplace(obj)) == null ||
                    (repCl = obj.getClass()) == cl)
                {
                    break;
                }
                cl = repCl;
            }
            if () {
                Object rep = replaceObject(obj);
                if (rep != obj && rep != null) {
                    cl = rep.getClass();
                    desc = ObjectStreamClass.lookup(cltrue);
                }
                obj = rep;
            }
            // if object replaced, run through original checks a second time
            if (obj != orig) {
                .assign(origobj);
                if (obj == null) {
                    writeNull();
                    return;
                } else if (!unshared && (h = .lookup(obj)) != -1) {
                    writeHandle(h);
                    return;
                } else if (obj instanceof Class) {
                    writeClass((Classobjunshared);
                    return;
                } else if (obj instanceof ObjectStreamClass) {
                    writeClassDesc((ObjectStreamClassobjunshared);
                    return;
                }
            }
            // remaining cases
            if (obj instanceof String) {
                writeString((Stringobjunshared);
            } else if (cl.isArray()) {
                writeArray(objdescunshared);
            } else if (obj instanceof Enum) {
                writeEnum((Enumobjdescunshared);
            } else if (obj instanceof Serializable) {
                writeOrdinaryObject(objdescunshared);
            } else {
                if () {
                    throw new NotSerializableException(
                        cl.getName() + "\n" + .toString());
                } else {
                    throw new NotSerializableException(cl.getName());
                }
            }
        } finally {
            --;
            .setBlockDataMode(oldMode);
        }
    }

    
Writes null code to stream.
    private void writeNull() throws IOException {
        .writeByte();
    }

    
Writes given object handle to stream.
    private void writeHandle(int handlethrows IOException {
        .writeByte();
        .writeInt( + handle);
    }

    
Writes representation of given class to stream.
    private void writeClass(Class clboolean unsharedthrows IOException {
        .writeByte();
        writeClassDesc(ObjectStreamClass.lookup(cltrue), false);
        .assign(unshared ? null : cl);
    }

    
Writes representation of given class descriptor to stream.
    private void writeClassDesc(ObjectStreamClass descboolean unshared)
        throws IOException
    {
        int handle;
        if (desc == null) {
            writeNull();
        } else if (!unshared && (handle = .lookup(desc)) != -1) {
            writeHandle(handle);
        } else if (desc.isProxy()) {
            writeProxyDesc(descunshared);
        } else {
            writeNonProxyDesc(descunshared);
        }
    }

    
Writes class descriptor representing a dynamic proxy class to stream.
    private void writeProxyDesc(ObjectStreamClass descboolean unshared)
        throws IOException
    {
        .assign(unshared ? null : desc);
        Class cl = desc.forClass();
        Class[] ifaces = cl.getInterfaces();
        .writeInt(ifaces.length);
        for (int i = 0; i < ifaces.lengthi++) {
            .writeUTF(ifaces[i].getName());
        }
        .setBlockDataMode(true);
        annotateProxyClass(cl);
        .setBlockDataMode(false);
        writeClassDesc(desc.getSuperDesc(), false);
    }

    
Writes class descriptor representing a standard (i.e., not a dynamic proxy) class to stream.
    private void writeNonProxyDesc(ObjectStreamClass descboolean unshared)
        throws IOException
    {
        .writeByte();
        .assign(unshared ? null : desc);
        if ( == ) {
            // do not invoke class descriptor write hook with old protocol
            desc.writeNonProxy(this);
        } else {
            writeClassDescriptor(desc);
        }
        Class cl = desc.forClass();
        .setBlockDataMode(true);
        annotateClass(cl);
        .setBlockDataMode(false);
        writeClassDesc(desc.getSuperDesc(), false);
    }

    
Writes given string to stream, using standard or long UTF format depending on string length.
    private void writeString(String strboolean unsharedthrows IOException {
        .assign(unshared ? null : str);
        long utflen = .getUTFLength(str);
        if (utflen <= 0xFFFF) {
            .writeByte();
            .writeUTF(strutflen);
        } else {
            .writeByte();
            .writeLongUTF(strutflen);
        }
    }

    
Writes given array object to stream.
    private void writeArray(Object array,
                            ObjectStreamClass desc,
                            boolean unshared)
        throws IOException
    {
        .writeByte();
        writeClassDesc(descfalse);
        .assign(unshared ? null : array);
        Class ccl = desc.forClass().getComponentType();
        if (ccl.isPrimitive()) {
            if (ccl == .) {
                int[] ia = (int[]) array;
                .writeInt(ia.length);
                .writeInts(ia, 0, ia.length);
            } else if (ccl == .) {
                byte[] ba = (byte[]) array;
                .writeInt(ba.length);
                .write(ba, 0, ba.lengthtrue);
            } else if (ccl == .) {
                long[] ja = (long[]) array;
                .writeInt(ja.length);
                .writeLongs(ja, 0, ja.length);
            } else if (ccl == .) {
                float[] fa = (float[]) array;
                .writeInt(fa.length);
                .writeFloats(fa, 0, fa.length);
            } else if (ccl == .) {
                double[] da = (double[]) array;
                .writeInt(da.length);
                .writeDoubles(da, 0, da.length);
            } else if (ccl == .) {
                short[] sa = (short[]) array;
                .writeInt(sa.length);
                .writeShorts(sa, 0, sa.length);
            } else if (ccl == .) {
                char[] ca = (char[]) array;
                .writeInt(ca.length);
                .writeChars(ca, 0, ca.length);
            } else if (ccl == .) {
                boolean[] za = (boolean[]) array;
                .writeInt(za.length);
                .writeBooleans(za, 0, za.length);
            } else {
                throw new InternalError();
            }
        } else {
            Object[] objs = (Object[]) array;
            int len = objs.length;
            .writeInt(len);
            if () {
                .push(
                    "array (class \"" + array.getClass().getName() +
                    "\", size: " + len  + ")");
            }
            try {
                for (int i = 0; i < leni++) {
                    if () {
                        .push(
                            "element of array (index: " + i + ")");
                    }
                    try {
                        writeObject0(objs[i], false);
                    } finally {
                        if () {
                            .pop();
                        }
                    }
                }
            } finally {
                if () {
                    .pop();
                }
            }
        }
    }

    
Writes given enum constant to stream.
    private void writeEnum(Enum en,
                           ObjectStreamClass desc,
                           boolean unshared)
        throws IOException
    {
        .writeByte();
        ObjectStreamClass sdesc = desc.getSuperDesc();
        writeClassDesc((sdesc.forClass() == Enum.class) ? desc : sdescfalse);
        .assign(unshared ? null : en);
        writeString(en.name(), false);
    }

    
Writes representation of a "ordinary" (i.e., not a String, Class, ObjectStreamClass, array, or enum constant) serializable object to the stream.
    private void writeOrdinaryObject(Object obj,
                                     ObjectStreamClass desc,
                                     boolean unshared)
        throws IOException
    {
        if () {
            .push(
                ( == 1 ? "root " : "") + "object (class \"" +
                obj.getClass().getName() + "\", " + obj.toString() + ")");
        }
        try {
            desc.checkSerialize();
            .writeByte();
            writeClassDesc(descfalse);
            .assign(unshared ? null : obj);
            if (desc.isExternalizable() && !desc.isProxy()) {
                writeExternalData((Externalizableobj);
            } else {
                writeSerialData(objdesc);
            }
        } finally {
            if () {
                .pop();
            }
        }
    }

    
Writes externalizable data of given object by invoking its writeExternal() method.
    private void writeExternalData(Externalizable objthrows IOException {
        Object oldObj = ;
        ObjectStreamClass oldDesc = ;
        PutFieldImpl oldPut = ;
         = obj;
         = null;
         = null;
        if () {
            .push("writeExternal data");
        }
        try {
            if ( == ) {
                obj.writeExternal(this);
            } else {
                .setBlockDataMode(true);
                obj.writeExternal(this);
                .setBlockDataMode(false);
                .writeByte();
            }
        } finally {
            if () {
                .pop();
            }
        }
         = oldObj;
         = oldDesc;
         = oldPut;
    }

    
Writes instance data for each serializable class of given object, from superclass to subclass.
    private void writeSerialData(Object objObjectStreamClass desc)
        throws IOException
    {
        ObjectStreamClass.ClassDataSlot[] slots = desc.getClassDataLayout();
        for (int i = 0; i < slots.lengthi++) {
            ObjectStreamClass slotDesc = slots[i].;
            if (slotDesc.hasWriteObjectMethod()) {
                Object oldObj = ;
                ObjectStreamClass oldDesc = ;
                PutFieldImpl oldPut = ;
                 = obj;
                 = slotDesc;
                 = null;
                if () {
                    .push(
                        "custom writeObject data (class \"" +
                        slotDesc.getName() + "\")");
                }
                try {
                    .setBlockDataMode(true);
                    slotDesc.invokeWriteObject(objthis);
                    .setBlockDataMode(false);
                    .writeByte();
                } finally {
                    if () {
                        .pop();
                    }
                }
                 = oldObj;
                 = oldDesc;
                 = oldPut;
            } else {
                defaultWriteFields(objslotDesc);
            }
        }
    }

    
Fetches and writes values of serializable fields of given object to stream. The given class descriptor specifies which field values to write, and in which order they should be written.
    private void defaultWriteFields(Object objObjectStreamClass desc)
        throws IOException
    {
        // REMIND: perform conservative isInstance check here?
        desc.checkDefaultSerialize();
        int primDataSize = desc.getPrimDataSize();
        if ( == null || . < primDataSize) {
             = new byte[primDataSize];
        }
        desc.getPrimFieldValues(obj);
        .write(, 0, primDataSizefalse);
        ObjectStreamField[] fields = desc.getFields(false);
        Object[] objVals = new Object[desc.getNumObjFields()];
        int numPrimFields = fields.length - objVals.length;
        desc.getObjFieldValues(objobjVals);
        for (int i = 0; i < objVals.lengthi++) {
            if () {
                .push(
                    "field (class \"" + desc.getName() + "\", name: \"" +
                    fields[numPrimFields + i].getName() + "\", type: \"" +
                    fields[numPrimFields + i].getType() + "\")");
            }
            try {
                writeObject0(objVals[i],
                             fields[numPrimFields + i].isUnshared());
            } finally {
                if () {
                    .pop();
                }
            }
        }
    }

    
Attempts to write to stream fatal IOException that has caused serialization to abort.
    private void writeFatalException(IOException exthrows IOException {
        /*
         * Note: the serialization specification states that if a second
         * IOException occurs while attempting to serialize the original fatal
         * exception to the stream, then a StreamCorruptedException should be
         * thrown (section 2.1).  However, due to a bug in previous
         * implementations of serialization, StreamCorruptedExceptions were
         * rarely (if ever) actually thrown--the "root" exceptions from
         * underlying streams were thrown instead.  This historical behavior is
         * followed here for consistency.
         */
        clear();
        boolean oldMode = .setBlockDataMode(false);
        try {
            .writeByte();
            writeObject0(exfalse);
            clear();
        } finally {
            .setBlockDataMode(oldMode);
        }
    }

    
Converts specified span of float values into byte values.
    // REMIND: remove once hotspot inlines Float.floatToIntBits
    private static native void floatsToBytes(float[] srcint srcpos,
                                             byte[] dstint dstpos,
                                             int nfloats);

    
Converts specified span of double values into byte values.
    // REMIND: remove once hotspot inlines Double.doubleToLongBits
    private static native void doublesToBytes(double[] srcint srcpos,
                                              byte[] dstint dstpos,
                                              int ndoubles);

    
Default PutField implementation.
    private class PutFieldImpl extends PutField {

        
class descriptor describing serializable fields
        private final ObjectStreamClass desc;
        
primitive field values
        private final byte[] primVals;
        
object field values
        private final Object[] objVals;

        
Creates PutFieldImpl object for writing fields defined in given class descriptor.
        PutFieldImpl(ObjectStreamClass desc) {
            this. = desc;
             = new byte[desc.getPrimDataSize()];
             = new Object[desc.getNumObjFields()];
        }
        public void put(String nameboolean val) {
            Bits.putBoolean(getFieldOffset(name.), val);
        }
        public void put(String namebyte val) {
            [getFieldOffset(name.)] = val;
        }
        public void put(String namechar val) {
            Bits.putChar(getFieldOffset(name.), val);
        }
        public void put(String nameshort val) {
            Bits.putShort(getFieldOffset(name.), val);
        }
        public void put(String nameint val) {
            Bits.putInt(getFieldOffset(name.), val);
        }
        public void put(String namefloat val) {
            Bits.putFloat(getFieldOffset(name.), val);
        }
        public void put(String namelong val) {
            Bits.putLong(getFieldOffset(name.), val);
        }
        public void put(String namedouble val) {
            Bits.putDouble(getFieldOffset(name.), val);
        }
        public void put(String nameObject val) {
            [getFieldOffset(nameObject.class)] = val;
        }
        // deprecated in ObjectOutputStream.PutField
        public void write(ObjectOutput outthrows IOException {
            /*
             * Applications should *not* use this method to write PutField
             * data, as it will lead to stream corruption if the PutField
             * object writes any primitive data (since block data mode is not
             * unset/set properly, as is done in OOS.writeFields()).  This
             * broken implementation is being retained solely for behavioral
             * compatibility, in order to support applications which use
             * OOS.PutField.write() for writing only non-primitive data.
             *
             * Serialization of unshared objects is not implemented here since
             * it is not necessary for backwards compatibility; also, unshared
             * semantics may not be supported by the given ObjectOutput
             * instance.  Applications which write unshared objects using the
             * PutField API must use OOS.writeFields().
             */
            if (ObjectOutputStream.this != out) {
                throw new IllegalArgumentException("wrong stream");
            }
            out.write(, 0, .);
            ObjectStreamField[] fields = .getFields(false);
            int numPrimFields = fields.length - .;
            // REMIND: warn if numPrimFields > 0?
            for (int i = 0; i < .i++) {
                if (fields[numPrimFields + i].isUnshared()) {
                    throw new IOException("cannot write unshared object");
                }
                out.writeObject([i]);
            }
        }

        
Writes buffered primitive data and object fields to stream.
        void writeFields() throws IOException {
            .write(, 0, .false);
            ObjectStreamField[] fields = .getFields(false);
            int numPrimFields = fields.length - .;
            for (int i = 0; i < .i++) {
                if () {
                    .push(
                        "field (class \"" + .getName() + "\", name: \"" +
                        fields[numPrimFields + i].getName() + "\", type: \"" +
                        fields[numPrimFields + i].getType() + "\")");
                }
                try {
                    writeObject0([i],
                                 fields[numPrimFields + i].isUnshared());
                } finally {
                    if () {
                        .pop();
                    }
                }
            }
        }

        
Returns offset of field with given name and type. A specified type of null matches all types, Object.class matches all non-primitive types, and any other non-null type matches assignable types only. Throws IllegalArgumentException if no matching field found.
        private int getFieldOffset(String nameClass type) {
            ObjectStreamField field = .getField(nametype);
            if (field == null) {
                throw new IllegalArgumentException("no such field " + name +
                                                   " with type " + type);
            }
            return field.getOffset();
        }
    }

    
Buffered output stream with two modes: in default mode, outputs data in same format as DataOutputStream; in "block data" mode, outputs data bracketed by block data markers (see object serialization specification for details).
    private static class BlockDataOutputStream
        extends OutputStream implements DataOutput
    {
        
maximum data block length
        private static final int MAX_BLOCK_SIZE = 1024;
        
maximum data block header length
        private static final int MAX_HEADER_SIZE = 5;
        
(tunable) length of char buffer (for writing strings)
        private static final int CHAR_BUF_SIZE = 256;

        
buffer for writing general/block data
        private final byte[] buf = new byte[];
        
buffer for writing block data headers
        private final byte[] hbuf = new byte[];
        
char buffer for fast string writes
        private final char[] cbuf = new char[];

        
block data mode
        private boolean blkmode = false;
        
current offset into buf
        private int pos = 0;

        
underlying output stream
        private final OutputStream out;
        
loopback stream (for data writes that span data blocks)
        private final DataOutputStream dout;

        
Creates new BlockDataOutputStream on top of given underlying stream. Block data mode is turned off by default.
        BlockDataOutputStream(OutputStream out) {
            this. = out;
             = new DataOutputStream(this);
        }

        
Sets block data mode to the given mode (true == on, false == off) and returns the previous mode value. If the new mode is the same as the old mode, no action is taken. If the new mode differs from the old mode, any buffered data is flushed before switching to the new mode.
        boolean setBlockDataMode(boolean modethrows IOException {
            if ( == mode) {
                return ;
            }
            drain();
             = mode;
            return !;
        }

        
Returns true if the stream is currently in block data mode, false otherwise.
        boolean getBlockDataMode() {
            return ;
        }
        /* ----------------- generic output stream methods ----------------- */
        /*
         * The following methods are equivalent to their counterparts in
         * OutputStream, except that they partition written data into data
         * blocks when in block data mode.
         */
        public void write(int bthrows IOException {
            if ( >= ) {
                drain();
            }
            [++] = (byteb;
        }
        public void write(byte[] bthrows IOException {
            write(b, 0, b.lengthfalse);
        }
        public void write(byte[] bint offint lenthrows IOException {
            write(bofflenfalse);
        }
        public void flush() throws IOException {
            drain();
            .flush();
        }
        public void close() throws IOException {
            flush();
            .close();
        }

        
Writes specified span of byte values from given array. If copy is true, copies the values to an intermediate buffer before writing them to underlying stream (to avoid exposing a reference to the original byte array).
        void write(byte[] bint offint lenboolean copy)
            throws IOException
        {
            if (!(copy || )) {           // write directly
                drain();
                .write(bofflen);
                return;
            }
            while (len > 0) {
                if ( >= ) {
                    drain();
                }
                if (len >=  && !copy &&  == 0) {
                    // avoid unnecessary copy
                    writeBlockHeader();
                    .write(boff);
                    off += ;
                    len -= ;
                } else {
                    int wlen = Math.min(len - );
                    System.arraycopy(boffwlen);
                     += wlen;
                    off += wlen;
                    len -= wlen;
                }
            }
        }

        
Writes all buffered data from this stream to the underlying stream, but does not flush underlying stream.
        void drain() throws IOException {
            if ( == 0) {
                return;
            }
            if () {
                writeBlockHeader();
            }
            .write(, 0, );
             = 0;
        }

        
Writes block data header. Data blocks shorter than 256 bytes are prefixed with a 2-byte header; all others start with a 5-byte header.
        private void writeBlockHeader(int lenthrows IOException {
            if (len <= 0xFF) {
                [0] = ;
                [1] = (bytelen;
                .write(, 0, 2);
            } else {
                [0] = ;
                Bits.putInt(, 1, len);
                .write(, 0, 5);
            }
        }
        /* ----------------- primitive data output methods ----------------- */
        /*
         * The following methods are equivalent to their counterparts in
         * DataOutputStream, except that they partition written data into data
         * blocks when in block data mode.
         */
        public void writeBoolean(boolean vthrows IOException {
            if ( >= ) {
                drain();
            }
            Bits.putBoolean(++, v);
        }
        public void writeByte(int vthrows IOException {
            if ( >= ) {
                drain();
            }
            [++] = (bytev;
        }
        public void writeChar(int vthrows IOException {
            if ( + 2 <= ) {
                Bits.putChar(, (charv);
                 += 2;
            } else {
                .writeChar(v);
            }
        }
        public void writeShort(int vthrows IOException {
            if ( + 2 <= ) {
                Bits.putShort(, (shortv);
                 += 2;
            } else {
                .writeShort(v);
            }
        }
        public void writeInt(int vthrows IOException {
            if ( + 4 <= ) {
                Bits.putInt(v);
                 += 4;
            } else {
                .writeInt(v);
            }
        }
        public void writeFloat(float vthrows IOException {
            if ( + 4 <= ) {
                Bits.putFloat(v);
                 += 4;
            } else {
                .writeFloat(v);
            }
        }
        public void writeLong(long vthrows IOException {
            if ( + 8 <= ) {
                Bits.putLong(v);
                 += 8;
            } else {
                .writeLong(v);
            }
        }
        public void writeDouble(double vthrows IOException {
            if ( + 8 <= ) {
                Bits.putDouble(v);
                 += 8;
            } else {
                .writeDouble(v);
            }
        }
        public void writeBytes(String sthrows IOException {
            int endoff = s.length();
            int cpos = 0;
            int csize = 0;
            for (int off = 0; off < endoff; ) {
                if (cpos >= csize) {
                    cpos = 0;
                    csize = Math.min(endoff - off);
                    s.getChars(offoff + csize, 0);
                }
                if ( >= ) {
                    drain();
                }
                int n = Math.min(csize - cpos - );
                int stop =  + n;
                while ( < stop) {
                    [++] = (byte[cpos++];
                }
                off += n;
            }
        }
        public void writeChars(String sthrows IOException {
            int endoff = s.length();
            for (int off = 0; off < endoff; ) {
                int csize = Math.min(endoff - off);
                s.getChars(offoff + csize, 0);
                writeChars(, 0, csize);
                off += csize;
            }
        }
        public void writeUTF(String sthrows IOException {
            writeUTF(sgetUTFLength(s));
        }
        /* -------------- primitive data array output methods -------------- */
        /*
         * The following methods write out spans of primitive data values.
         * Though equivalent to calling the corresponding primitive write
         * methods repeatedly, these methods are optimized for writing groups
         * of primitive data values more efficiently.
         */
        void writeBooleans(boolean[] vint offint lenthrows IOException {
            int endoff = off + len;
            while (off < endoff) {
                if ( >= ) {
                    drain();
                }
                int stop = Math.min(endoffoff + ( - ));
                while (off < stop) {
                    Bits.putBoolean(++, v[off++]);
                }
            }
        }
        void writeChars(char[] vint offint lenthrows IOException {
            int limit =  - 2;
            int endoff = off + len;
            while (off < endoff) {
                if ( <= limit) {
                    int avail = ( - ) >> 1;
                    int stop = Math.min(endoffoff + avail);
                    while (off < stop) {
                        Bits.putChar(v[off++]);
                         += 2;
                    }
                } else {
                    .writeChar(v[off++]);
                }
            }
        }
        void writeShorts(short[] vint offint lenthrows IOException {
            int limit =  - 2;
            int endoff = off + len;
            while (off < endoff) {
                if ( <= limit) {
                    int avail = ( - ) >> 1;
                    int stop = Math.min(endoffoff + avail);
                    while (off < stop) {
                        Bits.putShort(v[off++]);
                         += 2;
                    }
                } else {
                    .writeShort(v[off++]);
                }
            }
        }
        void writeInts(int[] vint offint lenthrows IOException {
            int limit =  - 4;
            int endoff = off + len;
            while (off < endoff) {
                if ( <= limit) {
                    int avail = ( - ) >> 2;
                    int stop = Math.min(endoffoff + avail);
                    while (off < stop) {
                        Bits.putInt(v[off++]);
                         += 4;
                    }
                } else {
                    .writeInt(v[off++]);
                }
            }
        }
        void writeFloats(float[] vint offint lenthrows IOException {
            int limit =  - 4;
            int endoff = off + len;
            while (off < endoff) {
                if ( <= limit) {
                    int avail = ( - ) >> 2;
                    int chunklen = Math.min(endoff - offavail);
                    floatsToBytes(voffchunklen);
                    off += chunklen;
                     += chunklen << 2;
                } else {
                    .writeFloat(v[off++]);
                }
            }
        }
        void writeLongs(long[] vint offint lenthrows IOException {
            int limit =  - 8;
            int endoff = off + len;
            while (off < endoff) {
                if ( <= limit) {
                    int avail = ( - ) >> 3;
                    int stop = Math.min(endoffoff + avail);
                    while (off < stop) {
                        Bits.putLong(v[off++]);
                         += 8;
                    }
                } else {
                    .writeLong(v[off++]);
                }
            }
        }
        void writeDoubles(double[] vint offint lenthrows IOException {
            int limit =  - 8;
            int endoff = off + len;
            while (off < endoff) {
                if ( <= limit) {
                    int avail = ( - ) >> 3;
                    int chunklen = Math.min(endoff - offavail);
                    doublesToBytes(voffchunklen);
                    off += chunklen;
                     += chunklen << 3;
                } else {
                    .writeDouble(v[off++]);
                }
            }
        }

        
Returns the length in bytes of the UTF encoding of the given string.
        long getUTFLength(String s) {
            int len = s.length();
            long utflen = 0;
            for (int off = 0; off < len; ) {
                int csize = Math.min(len - off);
                s.getChars(offoff + csize, 0);
                for (int cpos = 0; cpos < csizecpos++) {
                    char c = [cpos];
                    if (c >= 0x0001 && c <= 0x007F) {
                        utflen++;
                    } else if (c > 0x07FF) {
                        utflen += 3;
                    } else {
                        utflen += 2;
                    }
                }
                off += csize;
            }
            return utflen;
        }

        
Writes the given string in UTF format. This method is used in situations where the UTF encoding length of the string is already known; specifying it explicitly avoids a prescan of the string to determine its UTF length.
        void writeUTF(String slong utflenthrows IOException {
            if (utflen > 0xFFFFL) {
                throw new UTFDataFormatException();
            }
            writeShort((intutflen);
            if (utflen == (longs.length()) {
                writeBytes(s);
            } else {
                writeUTFBody(s);
            }
        }

        
Writes given string in "long" UTF format. "Long" UTF format is identical to standard UTF, except that it uses an 8 byte header (instead of the standard 2 bytes) to convey the UTF encoding length.
        void writeLongUTF(String sthrows IOException {
            writeLongUTF(sgetUTFLength(s));
        }

        
Writes given string in "long" UTF format, where the UTF encoding length of the string is already known.
        void writeLongUTF(String slong utflenthrows IOException {
            writeLong(utflen);
            if (utflen == (longs.length()) {
                writeBytes(s);
            } else {
                writeUTFBody(s);
            }
        }

        
Writes the "body" (i.e., the UTF representation minus the 2-byte or 8-byte length header) of the UTF encoding for the given string.
        private void writeUTFBody(String sthrows IOException {
            int limit =  - 3;
            int len = s.length();
            for (int off = 0; off < len; ) {
                int csize = Math.min(len - off);
                s.getChars(offoff + csize, 0);
                for (int cpos = 0; cpos < csizecpos++) {
                    char c = [cpos];
                    if ( <= limit) {
                        if (c <= 0x007F && c != 0) {
                            [++] = (bytec;
                        } else if (c > 0x07FF) {
                            [ + 2] = (byte) (0x80 | ((c >> 0) & 0x3F));
                            [ + 1] = (byte) (0x80 | ((c >> 6) & 0x3F));
                            [ + 0] = (byte) (0xE0 | ((c >> 12) & 0x0F));
                             += 3;
                        } else {
                            [ + 1] = (byte) (0x80 | ((c >> 0) & 0x3F));
                            [ + 0] = (byte) (0xC0 | ((c >> 6) & 0x1F));
                             += 2;
                        }
                    } else {    // write one byte at a time to normalize block
                        if (c <= 0x007F && c != 0) {
                            write(c);
                        } else if (c > 0x07FF) {
                            write(0xE0 | ((c >> 12) & 0x0F));
                            write(0x80 | ((c >> 6) & 0x3F));
                            write(0x80 | ((c >> 0) & 0x3F));
                        } else {
                            write(0xC0 | ((c >> 6) & 0x1F));
                            write(0x80 | ((c >> 0) & 0x3F));
                        }
                    }
                }
                off += csize;
            }
        }
    }

    
Lightweight identity hash table which maps objects to integer handles, assigned in ascending order.
    private static class HandleTable {
        /* number of mappings in table/next available handle */
        private int size;
        /* size threshold determining when to expand hash spine */
        private int threshold;
        /* factor for computing size threshold */
        private final float loadFactor;
        /* maps hash value -> candidate handle value */
        private int[] spine;
        /* maps handle value -> next candidate handle value */
        private int[] next;
        /* maps handle value -> associated object */
        private Object[] objs;

        
Creates new HandleTable with given capacity and load factor.
        HandleTable(int initialCapacityfloat loadFactor) {
            this. = loadFactor;
             = new int[initialCapacity];
             = new int[initialCapacity];
             = new Object[initialCapacity];
             = (int) (initialCapacity * loadFactor);
            clear();
        }

        
Assigns next available handle to given object, and returns handle value. Handles are assigned in ascending order starting at 0.
        int assign(Object obj) {
            if ( >= .) {
                growEntries();
            }
            if ( >= ) {
                growSpine();
            }
            insert(obj);
            return ++;
        }

        
Looks up and returns handle associated with given object, or -1 if no mapping found.
        int lookup(Object obj) {
            if ( == 0) {
                return -1;
            }
            int index = hash(obj) % .;
            for (int i = [index]; i >= 0; i = [i]) {
                if ([i] == obj) {
                    return i;
                }
            }
            return -1;
        }

        
Resets table to its initial (empty) state.
        void clear() {
            Arrays.fill(, -1);
            Arrays.fill(, 0, null);
             = 0;
        }

        
Returns the number of mappings currently in table.
        int size() {
            return ;
        }

        
Inserts mapping object -> handle mapping into table. Assumes table is large enough to accommodate new mapping.
        private void insert(Object objint handle) {
            int index = hash(obj) % .;
            [handle] = obj;
            [handle] = [index];
            [index] = handle;
        }

        
Expands the hash "spine" -- equivalent to increasing the number of buckets in a conventional hash table.
        private void growSpine() {
             = new int[(. << 1) + 1];
             = (int) (. * );
            Arrays.fill(, -1);
            for (int i = 0; i < i++) {
                insert([i], i);
            }
        }

        
Increases hash table capacity by lengthening entry arrays.
        private void growEntries() {
            int newLength = (. << 1) + 1;
            int[] newNext = new int[newLength];
            System.arraycopy(, 0, newNext, 0, );
             = newNext;
            Object[] newObjs = new Object[newLength];
            System.arraycopy(, 0, newObjs, 0, );
             = newObjs;
        }

        
Returns hash value for given object.
        private int hash(Object obj) {
            return System.identityHashCode(obj) & 0x7FFFFFFF;
        }
    }

    
Lightweight identity hash table which maps objects to replacement objects.
    private static class ReplaceTable {
        /* maps object -> index */
        private final HandleTable htab;
        /* maps index -> replacement object */
        private Object[] reps;

        
Creates new ReplaceTable with given capacity and load factor.
        ReplaceTable(int initialCapacityfloat loadFactor) {
             = new HandleTable(initialCapacityloadFactor);
             = new Object[initialCapacity];
        }

        
Enters mapping from object to replacement object.
        void assign(Object objObject rep) {
            int index = .assign(obj);
            while (index >= .) {
                grow();
            }
            [index] = rep;
        }

        
Looks up and returns replacement for given object. If no replacement is found, returns the lookup object itself.
        Object lookup(Object obj) {
            int index = .lookup(obj);
            return (index >= 0) ? [index] : obj;
        }

        
Resets table to its initial (empty) state.
        void clear() {
            Arrays.fill(, 0, .size(), null);
            .clear();
        }

        
Returns the number of mappings currently in table.
        int size() {
            return .size();
        }

        
Increases table capacity.
        private void grow() {
            Object[] newReps = new Object[(. << 1) + 1];
            System.arraycopy(, 0, newReps, 0, .);
             = newReps;
        }
    }

    
Stack to keep debug information about the state of the serialization process, for embedding in exception messages.
    private static class DebugTraceInfoStack {
        private final List<Stringstack;
        DebugTraceInfoStack() {
             = new ArrayList<String>();
        }

        
Removes all of the elements from enclosed list.
        void clear() {
            .clear();
        }

        
Removes the object at the top of enclosed list.
        void pop() {
            .remove(.size()-1);
        }

        
Pushes a String onto the top of enclosed list.
        void push(String entry) {
            .add("\t- " + entry);
        }

        
Returns a string representation of this object
        public String toString() {
            StringBuilder buffer = new StringBuilder();
            if (!.isEmpty()) {
                for(int i = .size(); i > 0; i-- ) {
                    buffer.append(.get(i-1) + ((i != 1) ? "\n" : ""));
                }
            }
            return buffer.toString();
        }
    }
New to GrepCode? Check out our FAQ X