Java.io.ObjectOutputStream.annotateClass() Method



Description

The java.io.ObjectOutputStream.annotateClass(Class<?> cl) can be implemented by subclasses 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.

Declaration

Following is the declaration for java.io.ObjectOutputStream.annotateClass() method.

protected void annotateClass(Class<?> cl)

Parameters

cl − The class to annotate custom data for.

Return Value

This method does not return a value.

Exception

NA

Example

The following example shows the usage of java.io.ObjectOutputStream.annotateClass() method.

package com.tutorialspoint;

import java.io.*;

public class ObjectOutputStreamDemo extends ObjectOutputStream {

   public ObjectOutputStreamDemo(OutputStream out) throws IOException {
      super(out);
   }
   
   public static void main(String[] args) {
      int i = 319874;
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStreamDemo oout = new ObjectOutputStreamDemo(out);

         // write something in the file
         oout.writeInt(i);
         oout.writeInt(1653984);
         oout.flush();
         
         // call annotateClass but it does nothing
         oout.annotateClass(Integer.class);

         // create an ObjectInputStream for the file we created before
         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));

         // read and print an int
         System.out.println("" + ois.readInt());

         // read and print an int
         System.out.println("" + ois.readInt());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result −

319874
1653984
java_io_objectoutputstream.htm
Advertisements