JacoSolari
JacoSolari

Reputation: 1394

What is the difference of annotating @Builder on constructor or on class declaration? (Lombok)

What is the difference between these two usage of @Builder?

import lombok.*;

class BuilderAnnotationOnConstructor{

    Integer fieldOne, fieldTwo;

    @Builder
    public BuilderAnnotationOnConstructor(int fieldOne, int fieldTwo) {
        this.fieldOne = fieldOne;
        this.fieldTwo = fieldTwo;
    }
}

@Builder
class BuilderAnnotationOnClass{

    Integer fieldOne, fieldTwo;

    public BuilderAnnotationOnClass(int fieldOne, int fieldTwo) {
        this.fieldOne = fieldOne;
        this.fieldTwo = fieldTwo;
    }
}

They both compile and run fine but I have noticed weird behaviors in the second case when the annotation is on the class declaration (e.g. in a large project of mine, attributes values assigned to wrong/swapped variable names; unfortunately I was not able to reproduce these behaviors in this simple example)

Upvotes: 4

Views: 1354

Answers (1)

Rémi Navarro
Rémi Navarro

Reputation: 44

From Lombok doc :

*Now that the "method" mode is clear, putting a @Builder annotation on a constructor functions similarly; effectively, constructors are just static methods that have a special syntax to invoke them: Their 'return type' is the class they construct, and their type parameters are the same as the type parameters of the class itself

Finally, applying @Builder to a class is as if you added @AllArgsConstructor(access = AccessLevel.PACKAGE) to the class and applied the @Builder annotation to this all-args-constructor. This only works if you haven't written any explicit constructors yourself. If you do have an explicit constructor, put the @Builder annotation on the constructor instead of on the class. Note that if you put both @Value and @Builder on a class, the package-private constructor that @Builder wants to generate 'wins' and suppresses the constructor that @Value wants to make. *

from https://projectlombok.org/features/Builder

Upvotes: 2

Related Questions