Maxim Kirilov
Maxim Kirilov

Reputation: 2739

Add default public constructor to generated builder inner class

I am using Lombok framework for boilerplate code generation, for example:

import lombok.*;


@Builder
@Value
public final class SocketConfig {

    @Builder.Default
    private int soTimeoutMilliseconds = 0;

    @Builder.Default
    private boolean soReuseAddress = false;

    @Builder.Default
    private int soLingerSeconds = -1;

    private boolean soKeepAlive;

    @Builder.Default
    private boolean tcpNoDelay = false;

} 

In order to create builder instances I used to invoke SocketConfig.builder(). But for better integration with spring beans creation I tried to create a FactoryBean. But got a compilation error due to lack of default constructor on the builder class, didn't find any documentation about it. Is it possible with Lombok? I mean to create a default constructor on the builder not on the original class. In other words, I want 2 options to create the builder instance: SocketConfig.builder() or through new SocketConfig.SocketConfigBuilder().

import org.springframework.beans.factory.FactoryBean;

public class SocketConfigFactoryBean extends SocketConfig.SocketConfigBuilder implements FactoryBean<SocketConfig> {



    @Override
    public SocketConfig getObject() throws Exception {
        return build();
    }

    @Override
    public Class<?> getObjectType() {
        return SocketConfig.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

Upvotes: 0

Views: 1139

Answers (1)

pzaenger
pzaenger

Reputation: 11984

Use the annotation NoArgsConstructor:

Generates a no-args constructor. Will generate an error message if such a constructor cannot be written due to the existence of final fields.

Read also this.

Upvotes: 1

Related Questions