ObjectInputStream enableResolveObject() method in Java with examples
The enableResolveObject() method of the ObjectInputStream class in Java is used to enables the stream to do replacement of objects read from the stream. When enabled, the resolveObject(java.lang.Object) method is called for every object being deserialized.
Syntax:
protected boolean enableResolveObject(
boolean enable)
Parameters: This method accepts only single parameter.
- enable: This parameter is set to true to enable use of resolveObject() for each object being deserialized.
Return Value: This method returns the previous setting before this method was invoked.
Errors and Exceptions: The function throws SecurityException if a security manager exists and its checkPermission method denies enabling the stream to do replacement of objects read from the stream.
Below program illustrate the above method:
Program 1:
Java
import java.io.*;
public class GFG
extends ObjectInputStream {
public GFG(InputStream in)
throws IOException
{
super (in);
}
public static void main(String[] args)
{
String s = "Geeksforgeeks" ;
try {
FileOutputStream out
= new FileOutputStream( "Shubham.txt" );
ObjectOutputStream out1
= new ObjectOutputStream(out);
out1.writeUTF(s);
out1.flush();
GFG example
= new GFG(
new FileInputStream( "Shubham.txt" ));
System.out.println(
example
.resolveObject(
example.readUTF()));
System.out.println(
example
.enableResolveObject( true ));
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
Output:
Program 2:
Java
import java.io.*;
import java.io.InputStream;
public class GFG
extends ObjectInputStream {
public GFG(InputStream in)
throws IOException
{
super (in);
}
public static void main(String[] args)
throws IOException
{
int [] array = { 1 , 34 , 23 , 425 , 69 , 22 };
try {
FileOutputStream out
= new FileOutputStream( "Shubham.txt" );
DataOutputStream out1
= new DataOutputStream(out);
for ( int val : array) {
out1.writeInt(val);
}
out1.flush();
DataInputStream example
= new DataInputStream(
new FileInputStream( "Shubham.txt" ));
for ( int i = 0 ; i <= array.length; i++) {
int c = example.readInt();
System.out.print(c + " " );
}
System.out.print( "\n" );
}
catch (Exception ex) {
}
}
}
|
Output:
Reference:
https://docs.oracle.com/javase/10/docs/api/java/io/ObjectInputStream.html#enableResolveObject(boolean)
Last Updated :
05 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...