Search code examples
javatostringlombok

Include only one property of nested object to toString method using Lombok


i have a following case:

@Data
public class Human{
   private long id;
   private Pet pet;
   //other properties...
}
@Data
public class Pet{
   private long id;
   private Human owner;
   //other properties...
}

I use lombok dependency and when toString is used, application throws java.lang.StackOverflowError. I know I can use @ToString.Exclude to exclude given field, but in such case i would like to have only a nested object's id proeprty to be shown in a toString method.
In other words, if an object's toString calls it's nested property toString, then (and only then) I want to see only that object id. But if i call that's object toString not from a parent object, I want to see a regular toString.
I know that i can define toString, equals and hashCode methods by myself this way, but is this possible to tell lombok to do that?


Solution

  • One way would be to add a getter for the pet/owner IDs, and mark that as @ToString.Include:

    @Data
    class Human{
        private long id;
    
        @ToString.Exclude
        @EqualsAndHashCode.Exclude
        private Pet pet;
    
        @ToString.Include
        public long petId() { return pet.getId(); }
    
        //other properties...
    }
    
    @Data
    class Pet{
        private long id;
    
        @ToString.Exclude
        @EqualsAndHashCode.Exclude
        private Human owner;
    
        @ToString.Include
        public long ownerId() { return owner.getId(); }
    }
    

    Usage:

    var human = new Human();
    var pet = new Pet();
    human.setPet(pet);
    pet.setOwner(human);
    System.out.println(human);
    
    // Output:
    // Human(id=0, petId=0)
    

    Note that you might also want to mark pet and owner as @EqualsAndHashCode.Exclude, because otherwise equals and hashCode might also cause stack overflows in some situations.