我正在尝试使用 WriteObject 方法编写 pojo 类的实例。当我写这样的代码时:
private void writeObject(ObjectOutputStream oos) throws IOException,ClassNotFoundException{
oos.defaultWriteObject();
oos.writeObject(this);
}
它工作正常,但是当我尝试创建一个新的本地对象并将其传递给 writeObject 方法时,它失败了
线程“主”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;
}
}