Lombok - java.lang.StackOverflowError: null on toString method

后端 未结 2 1659
遥遥无期
遥遥无期 2021-02-19 14:47

I have two classes Product and Categorie. When I would like to modify the list of products in categorie with categoryRepository.save(c1) a

2条回答
  •  一个人的身影
    2021-02-19 15:26

    I assume the @ToString annotation tells some tool you’re using (Lombok?) to generate a toString method that prints the values of all the fields. Each of the classes refer to the other: Product has a Categorie and Categorie has a list of Product instances. So when the toString implementation prints a Categorie, it calls toString on each Product, which then calls toString on its Categorie, etc. Since Product presumably refers to a Categorie which includes that Product in its products list, the toString calls bounce back and forth until the stack overflows. The solution is to avoid printing either Categorie,products or Product.categorie from the toString method. If you’re using Lombok, try annotating Categorie.products with @ToString.Exclude.

提交回复
热议问题