Lombok: How to specify a one arg constructor?

Lombok doesn't let you to specify the fields exactly, but there are 3 annotations to choose from. With

@RequiredArgsConstructor class MyClass {
    private final String param;
    private Integer count;
}

you can get it. An argument is required if it's not initialized inline and final or @NonNull.


I didn't find in documentation

How about this: http://projectlombok.org/features/Constructor.html ?

You have to initialize all variables which should not be part of the constructor.

@RequiredArgsConstructor generates a constructor with 1 parameter for each field that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared. For those fields marked with @NonNull, an explicit null check is also generated.

So the following should create an one argument (param) constructor:

@RequiredArgsConstructor class MyClass {
     private String param;
     private Integer count = -1;
}

@RequiredArgsConstructor and @NonNull are two important keys to solve the problem above. Because @RequiredArgsConstructor creates a constructor with fields which are annotated by @NonNull annotation.

@RequiredArgsConstructor
class MyClass {
    @NonNull
    private String param;
    private Integer count;
}

This is equivalent to:

class MyClass {
    private String param;
    private Integer count;

    public MyClass(String param) {
        this.param = param;
    }
}

Tags:

Java

Lombok