类循环依赖引起的栈溢出
程序员文章站
2022-06-01 13:37:28
...
测试代码:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Arrays;
import java.util.List;
/**
* 类循环依赖引起的栈溢出
*/
public class ClassCycleTest {
/**
* 员工类,这里有部门类集合
*/
static class Employee {
private String name;
private Dept dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Dept getDept() {
return dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public Employee(String name, Dept dept) {
this.name = name;
this.dept = dept;
}
}
/**
* 部门类,里面有员工类集合
*/
static class Dept {
private String deptName;
private List<Employee> employeeList;
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public Dept(String deptName) {
this.deptName = deptName;
}
}
public static void main(String[] args) throws JsonProcessingException {
Dept d = new Dept("测试部门");
Employee employee1 = new Employee("张三", d);
Employee employee2 = new Employee("李四", d);
//设值
d.setEmployeeList(Arrays.asList(employee1, employee2));
//对象转string
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(objectMapper.writeValueAsString(d));
}
}
运行结果如下:
可以看到是由于递归引起的栈溢出,而这里会产生递归的原因,就是因为类之间存在着循环依赖,相互之间无限转化,造成了无限递归的结果,无数的栈帧产生,最终导致了栈溢出。