ObjectInputStream resolveClass() Method in Java
The java.io.ObjectInputStream.resolveClass(ObjectStreamClass desc) method calls the class of the specified object stream class description.ObjectInputStream resolveClass() method in Java can also be used in case of subclasses.
ObjectInputStream resolveClass() Method in Java
The Declaration of the method:
protected Class<?> resolveClass(ObjectStreamClass desc)
The Parameter of the method:
The parameter of this method is desc. It is an instance of class ObjectStreamClass.
The Return value of the method:
Also, it returns a Class object that corresponds to desc.
Exception:
Most importantly, there are two exceptions in this class as stated below:
- ClassNotFoundException − If the class of a serialized object is absent.
- IOException − If it is the Input/Output exceptions.
Sample Code:
Below is an easy and simple implementation of ObjectInputStream resolveClass() Method in Java.
import java.io.*; public class ObjectInputStreamCode extends ObjectInputStream { public ObjectInputStreamCode(InputStream in) throws IOException { super(in); } public static void main(String[] args) { String str = "Hello! Welcome to CodeSpeedy.Happy Learning!"; try { // create a new file FileOutputStream o = new FileOutputStream("myFile.txt"); ObjectOutputStream out = new ObjectOutputStream(o); // write something in the file out.writeUTF(str); out.flush(); // create an ObjectInputStream for the created file ObjectInputStreamCode oo = new ObjectInputStreamCode(new FileInputStream("myFile.txt")); // read and print an object and make the string System.out.println("" + (String) oo.readUTF()); // get the class for string along with that print the name ObjectStreamClass myStreamClass = ObjectStreamClass.lookup(Integer.class); System.out.println("" + oo.resolveClass(myStreamClass).getName()); } catch (Exception exp) { exp.printStackTrace(); } } }
Output:
Below is the output for the above code.
Hello! Welcome to CodeSpeedy.Happy Learning!
java.lang.Integer
Know: Class and Object in Java
Leave a Reply