Java.io.ObjectInputStream.resolveClass() Method



Description

The java.io.ObjectInputStream.resolveClass(ObjectStreamClass desc) method loads the local class equivalent of the specified stream class description. Subclasses may implement this method to allow classes to be fetched from an alternate source.

Declaration

Following is the declaration for java.io.ObjectInputStream.resolveClass() method.

protected Class<?> resolveClass(ObjectStreamClass desc)

Parameters

desc − An instance of class ObjectStreamClass.

Return Value

This method returns a Class object corresponding to desc.

Exception

  • IOException − Any of the usual Input/Output exceptions.

  • ClassNotFoundException − If class of a serialized object cannot be found.

Example

The following example shows the usage of java.io.ObjectInputStream.resolveClass() method.

package com.tutorialspoint;

import java.io.*;

public class ObjectInputStreamDemo extends ObjectInputStream {

   public ObjectInputStreamDemo(InputStream in) throws IOException {
      super(in);
   }

   public static void main(String[] args) {
      String s = "Hello World";
      
      try {
         // create a new file with an ObjectOutputStream
         FileOutputStream out = new FileOutputStream("test.txt");
         ObjectOutputStream oout = new ObjectOutputStream(out);

         // write something in the file
         oout.writeUTF(s);
         oout.flush();

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

         // read and print an object and cast it as string
         System.out.println("" + (String) ois.readUTF());

         // get the class for string and print the name
         ObjectStreamClass streamClass = ObjectStreamClass.lookup(Integer.class);
         System.out.println("" + ois.resolveClass(streamClass).getName());
      } catch (Exception ex) {
         ex.printStackTrace();
      }
   }
}

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

Hello World
java.lang.Integer
java_io_objectinputstream.htm
Advertisements