我正在尝试使用WriteObject方法编写POJO类的实例。当我编写以下代码时:
private void writeObject(ObjectOutputStream oos) throws IOException,ClassNotFoundException{
oos.defaultWriteObject();
oos.writeObject(this);
}
它的运行很好,但是当我尝试创建一个新的本地对象并将其传递给writeObject方法时,它会出现失败:
Exception in thread "main" java.lang.StackOverflowError
请有人解释一下为什么它会不断递归调用writeObject方法?
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;
}
}