title: How to override ObjectOutputStream.writeStreamHeader()?
body: <p>The method <code>ObjectOutputStream.writeStreamHeader()</code> can be overridden to prepend or append data to the header.  However, if that data is based on an argument passed to the derived class's constructor like:</p>
  
  <pre><code>public class MyObjectOutputStream extends ObjectOutputStream {
  
      public MyObjectOutputStream( int myData, OutputStream out ) throws IOException {
          super( out );
          m_myData = myData;
      }
  
      protected void writeStreamHeader() throws IOException {
          write( m_myData );            // WRONG: m_myData not initialized yet
          super.writeStreamHeader();
      }
  
      private final int m_myData;
  }
  </code></pre>
  
  <p>it doesn't work because <code>super()</code> is called before <code>m_myData</code> is initialized and <code>super()</code> calls <code>writeStreamHeader()</code>.  The only way I can think to work around this is by using <code>ThreadLocal</code> like:</p>
  
  <pre><code>public class MyObjectOutputStream extends ObjectOutputStream {
  
      public MyObjectOutputStream( int myData, OutputStream out ) throws IOException {
          super( thunk( myData, out ) );
      }
  
      protected void writeStreamHeader() throws IOException {
          write( m_myData.get().intValue() );
          super.writeStreamHeader();
      }
  
      private static OutputStream thunk( int myData, OutputStream out ) {
          m_myData.set( myData );
          return out;
      }
  
      private static final ThreadLocal&lt;Integer&gt; m_myData = new ThreadLocal&lt;Integer&gt;();
  }
  </code></pre>
  
  <p>This seems to work, but is there a better (less clunky) way?</p>