I am trying to write a instance of pojo class by using WriteObject method. when i write code like this :
private void writeObject(ObjectOutputStream oos) throws IOException,ClassNotFoundException{
oos.defaultWriteObject();
oos.writeObject(this);
}
It works fine but when I try and create a new local object and pass it to writeObject method it fails with
Exception in thread "main" java.lang.StackOverflowError
can some one please explain why it keeps calling writeObject method again and again recursively?
class Employee implements Serializable{
private String name;
private int age;
private void readObject(ObjectInputStream ois) throws IOException,ClassNotFoundException{
ois.defaultReadObject();
Employee emp = (Employee)ois.readObject();
emp.toString();
}
private void writeObject(ObjectOutputStream oos) throws IOException,ClassNotFoundException{
oos.defaultWriteObject();
Employee emp = new Employee("sumit",10);
oos.writeObject(emp);
}
public Employee(){
}
public Employee(String name, int age){
this.name = name;
this.age = age;
}
}
It is because of the fact that you are overriding writeObject
method in your Employee
class. So, when you create the Employee
object and try to write it using writeObject
method, it is called recursively leading to StackOverflow
error.
But, when you do not write Employee
object the code executes properly.
---Edit as per the clarification asked in comment
In your Employee
class, you are overriding the writeObject
method , so , whenever, you try to invoke ObjectOutputStream.writeObject
with Employee
as parameter, your overridden method will be invoked. Now in your overridden writeObject
in Employee
class, you are again calling ObjectOutputStream.writeObject
( oos.writeObject(emp);
) with Employee as parameter, thus, writeObject
method of Employee
class gets recursively called (with new Employee object everytime)and you get stackoverflow error.
Now in case when you try to call recursively this
keyword, it is because of the fact that you try to invoke ObjectOutputStream.writeObject
with the same instance of Employee
class. As per the ObjectOutputStream.writeObject
documentation at below mentioned link :
https://docs.oracle.com/javase/7/docs/api/java/io/ObjectOutputStream.html
Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
Infact, if you try the below code in your main method :
Employee emp = new Employee("sumit",10);
oos.writeObject(emp);
oos.writeObject(emp);
i.e if you invoke writeObject
multiple times on same object, it is invoked only once.