Reputation: 1143
I'm currently building a Java application and using Lombok annotations to reduce boilerplate. I'm running into problems, however, when using the @Singular
and @NonNull
annotations together. For example, let's look at the following example class:
@Builder
class Classroom {
@Singular @NonNull
private List<String> students;
}
I would like the @NonNull annotation to protect from adding null
elements singularly, like so:
Classroom.builder()
.student("Sally")
.student("Joe")
.student(null)
.build();
However, even with the annotation, the null
element is still added to the list when the Classroom
object is built. Is there an easy way, using Lombok annotations, to mark singular elements as NonNull, or am I going to need to drop the annotations and implement that type of protection myself?
Upvotes: 3
Views: 2882
Reputation: 62683
According to the Lombock documentation :
You can use @NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.
So you have to put the @NonNull
annotation on the parameter of the student
method (in the builder class) and not on the private field students
(in the Classroom class).
public student(@NonNull String name){
students.add(name);
}
Upvotes: 1