Why This Happens
When two classes reference each other and both include the other in toString(), printing either object creates infinite recursion. This commonly happens with bidirectional JPA relationships (Parent has List<Child>, Child has Parent) where Lombok @ToString or IDE-generated toString includes all fields.
The Problem
class Parent {
List<Child> children;
public String toString() { return "Parent{children=" + children + "}"; }
}
class Child {
Parent parent;
public String toString() { return "Child{parent=" + parent + "}"; } // Infinite loop!
}The Fix
class Parent {
List<Child> children;
public String toString() { return "Parent{children=" + children + "}"; }
}
class Child {
Parent parent;
public String toString() { return "Child{parentId=" + parent.getId() + "}"; } // No recursion
}Step-by-Step Fix
- 1
Identify the recursive toString
Look at the stack trace for repeated toString() calls between two or more classes.
- 2
Find the circular reference
Identify bidirectional relationships where both classes include each other in toString().
- 3
Break the cycle
Exclude the back-reference from toString(), use only IDs, or use @ToString.Exclude in Lombok.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free