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
writeObjectmethod in yourEmployeeclass. So, when you create theEmployeeobject and try to write it usingwriteObjectmethod, it is called recursively leading toStackOverflowerror.But, when you do not write
Employeeobject the code executes properly.---Edit as per the clarification asked in comment
In your
Employeeclass, you are overriding thewriteObjectmethod , so , whenever, you try to invokeObjectOutputStream.writeObjectwithEmployeeas parameter, your overridden method will be invoked. Now in your overriddenwriteObjectinEmployeeclass, you are again callingObjectOutputStream.writeObject(oos.writeObject(emp);) with Employee as parameter, thus,writeObjectmethod ofEmployeeclass gets recursively called (with new Employee object everytime)and you get stackoverflow error.Now in case when you try to call recursively
thiskeyword, it is because of the fact that you try to invokeObjectOutputStream.writeObjectwith the same instance ofEmployeeclass. As per theObjectOutputStream.writeObjectdocumentation 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 :
i.e if you invoke
writeObjectmultiple times on same object, it is invoked only once.