Constructors in Lombok

If I have a class with three instance variables and a final variable of one instance.

Will I be restricted from instantiating this class using a no-argument constructor?

public @Data class Employee {

    private Integer empId;

    private String empName;

    private Country country;

    private final Integer var;

}

      

When trying to compile the following line

Employee emp = new Employee();

      

Then I got this error

an argument is required to match Employee (Integer).

+3


source to share


4 answers


Yes, this will restrict the use of the no-args constructor unless you initialize the final variable. If you initialize a final variable, it will create an instance of that class using the default no-argument constructor. But no setter will be generated for this final variable, however a getter will be generated. Even if we use @NoArgsConstructor

, it will give a compiler error final variable may not be initialized

.



+2


source


Yours Integer var

is final. The final variable can only be set in the constructor or in the initializer.

So in this case you cannot do with the constructor with lombok, you need to initialize your final variable first



private final Integer var = someValue;

      

+3


source


Your variable var

is final. Remove the ending so you can reassign the link var

.

+2


source


Short answer

yes , you are forbidden to instantiate this class using a no-argument constructor.

Long answer

The documentation for@Data

:

@Data is a handy annotation that ties the @ToString, @EqualsAndHashCode, @ Getter / @ Setter and @RequiredArgsConstructor functions together

@RequiredArgsConstructor

is
:

@RequiredArgsConstructor generates a 1-parameter constructor for each field that requires special handling. All uninitialized final fields receive a parameter , as well as any fields marked @NonNull that are not initialized where they are declared.

As you should know, Java does not create a default no-argument constructor if you have already defined your own constructor and with the Lombok annotation @Data

you have.

You can add Lombok explicitly @NoArgsConstructor

, however:

@NoArgsConstructor will generate a parameterless constructor. If this is not possible (due to trailing fields), a compiler error will be the result instead

+1


source







All Articles