Search code examples
javaoopdesign-patternslombokbuilder

How to initialize builder class members with dummy values while calling cls.builder.param().build()


I need to initialize my builder class members with some Dummy values while calling .param()

@Builder
public class MyQuery {
       private String param1;
       private String param1;
       private String param1;
       private String param1;
       ...
       private String param100;
}

When I call the builder class like below, I want them to be initialized with some dummy value(or empty string) and the rest should be null. If I use the LOMBOK builder, it has to be initialized with some value as .param1("some string"). Is there any library which can help me here.

    MyQuery query = MyQuery.builder()
            .param1()
            .param2()
            .param3()
            .build();

whichever parameter I call, should have some dummy value(non-null, could be empty as well).


Solution

  • After going through the lombok builder doc, I realized that I could do something as follows. Lombok will not generate the resources if a resource with the same name already exists. This approach will still reduce some of the boiler plate codes.

    import lombok.Builder;
    
        @Builder
        public class MyQuery {
    
            private static final String SOME_STRING = "This is needed"; 
            private String paramWithNoSpecialCase // This is any other parameter, lombok will generate the builder for this.
            private String param1;
            private String param2;
            private String param3;
    
    
            public static class MyQueryBuilder {
    
                public MyQuery.MyQueryBuilder param1() {
                    this.param1 = SOME_STRING;
                    return this;
                }
                public MyQuery.MyQueryBuilder param2() {
                    this.param1 = SOME_STRING;
                    return this;
                }
                public MyQuery.MyQueryBuilder param3() {
                    this.param1 = SOME_STRING;
                    return this;
                }
            }
        }