Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to set 'not null' for all params of @AllArgsConstructor (lombok)

Tags:

java

lombok

I'm using the @AllArgsConstructor annotation in my class and want to be sure that arguments will be not null. Is there a way to modify this annotation to make this possible, or I should implement constractor? Thanks

@Getter
@Setter
@ToString
@AllArgsConstructor
public class Contact {

    private String name;
    private String phoneNumber;

}

...

<lombok.version>1.16.18</lombok.version>
like image 587
IKo Avatar asked Dec 13 '17 16:12

IKo


People also ask

Can we use @NoArgsConstructor and @AllArgsConstructor together?

But if you add a constructor with parameters (or @AllArgsConstructor ), then you'll need to add a no args constructor (or @NoArgsConstructor ) as well, for JPA/Hibernate to work.

What is all args constructor Lombok?

An all-args constructor requires one argument for every field in the class. Complete documentation is found at the project lombok features page for @Constructor. Even though it is not listed, this annotation also has the onConstructor parameter.

What is AllArgsConstructor annotation?

The @AllArgsConstructor annotation generates a constructor with one parameter for every field in the class. Fields that are annotated with @NonNull result in null checks with the corresponding parameters in the constructor. The annotation won't generate a parameter for the static and initialized final fields.

What is the use of @NoArgsConstructor and @AllArgsConstructor?

The constructor will throw a NullPointerException if any of the parameters intended for the fields marked with @NonNull contain null . The order of the parameters match the order in which the fields appear in your class. @AllArgsConstructor generates a constructor with 1 parameter for each field in your class.


2 Answers

Yes, you have to use @ NonNull on such fields, it will result in a null check in the generated constructor.

like image 69
Adam Siemion Avatar answered Nov 07 '22 17:11

Adam Siemion


@RequiredArgsConstructor

Generates a constructor with required arguments. Required arguments are final fields and fields with constraints such as @NonNull. Complete documentation is found at the project lombok features page for @Constructor . Even though it is not listed, this annotation also has the onConstructor parameter. See the full documentation for more details.

like image 2
Sindre Avatar answered Nov 07 '22 16:11

Sindre