I just wanted to post a note about using Lombok generated toString()
with circular relationships (in my case, I was implementing
bidirectional JPA relationship). If an object with circular
relationship is printed, or as in my case, inspected in debugger
(causing toString() to be called), it throws StackOverflowError, as
the toString() methods between the two objects result in an endless
loop. Telling Lombok to ignore either of the fields causing the
circular relationship removes this problem. Try it out like this:
@Data
class Address {
Municipality municipality;
}
@Data
@ToString(exclude = "addresses") // Without this we get
StackOverflowError
class Municipality {
Set<Address> addresses = new HashSet<Address>();
public void addAddress(Address a) {
addresses.add(a);
}
}
public class JavaTest {
public static void main(String[] args) {
Address address = new Address();
Municipality municipality = new Municipality();
municipality.addAddress(address);
address.setMunicipality(municipality);
System.out.println(municipality);
System.out.println("Done.");
}
}
Of course this is not a bug or anything. I just failed to see this
beforehand and wanted to post a note if anyone else ever happens to
try google this...
Tuukka
Good point about putting it up so its googlable. Thanks, Tuukka!