2

Given the following Lombok-annotated class:

@Builder
public class User {

    private String username;
}

I created a utility class for creating User objects in tests:

public class UserTestUtils {

    public static final String DEFAULT_USERNAME = "Foo Bar";

    public static User.UserBuilder aDefaultUser() {
        return User.builder().username(DEFAULT_USERNAME);
    }
}

Now I can call this in my test:

User user = aDefaultUser().build();

I'd like to enrich this utility class with a method which does not return a User object but a JSON string representation like this:

User user = aDefaultUser().toJsonString();

Is it possible to add a custom toJsonString() method to the User.UserBuilder?

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

2

Yes. Just define a static class named UserBuilder, and lombok will add the methods:

    @Builder
    public class User {
    
        private String username;
    
        public static class UserBuilder {
    
            String toJsonString() {
                return "";
            }
        }
    }

If you inspect the generated code, you will find:

    public static class UserBuilder {
        @Generated
        private String username;

        String toJsonString() {
            return "";
        }

        @Generated
        UserBuilder() {
        }

        @Generated
        public UserBuilder username(final String username) {
            this.username = username;
            return this;
        }

        @Generated
        public User build() {
            return new User(this.username);
        }

        @Generated
        public String toString() {
            return "User.UserBuilder(username=" + this.username + ")";
        }
    }

The mechanism is similar to defining custom setters

Benoit
  • 5,118
  • 2
  • 24
  • 43