I am using Lombok for my project. My model looks like:
@Builder
@Data @AllArgsConstructor
public class ScreenDefinitionDTO {
@Singular
private List<ScreenDeclaration> screens;
}
I want to do next operation:
String screenName = ctx.screenName().getText();
ScreenDeclaration declaration = ParsingUtils
.buildScreenDeclaration(StringUtils.trim(screenName));
Where instance is created:
public static ScreenDefinitionDTO buildEmptyScreenDTO() {
return ScreenDefinitionDTO.builder()
.screens(new ArrayList<>())
.build();
}
Finally, I got:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
When I changed creating the instance without Lombok builder pattern everything is fine:
public static ScreenDefinitionDTO buildEmptyScreenDTO() {
return new ScreenDefinitionDTO(new ArrayList<>());
}
I couldn't understand what is wrong with Lombok's builder pattern?
Project Lombok's @Builder is a helpful mechanism for using the Builder pattern without writing boilerplate code. We can apply this annotation to a Class or a method. In this quick tutorial, we'll look at the different use cases for @Builder.
Lombok offers various annotations aimed at replacing Java code that is well known for being boilerplate, repetitive, or tedious to write. For example, by using Lombok, you can avoid writing constructors with no arguments, toString() , equals() , and hashCode() methods by simply adding a few annotations.
@Builder can be placed on a class, or on a constructor, or on a method. While the "on a class" and "on a constructor" mode are the most common use-case, @Builder is most easily explained with the "method" use-case.
Annotation Type Singular The singular annotation is used together with @Builder to create single element 'add' methods in the builder for collections.
Try this:
@Builder
@Data @AllArgsConstructor
public class ScreenDefinitionDTO {
@Builder.Default
private List<ScreenDeclaration> screens = new ArrayList<>();
}
This way you are telling lombok to, on build, initialize screens
with an empty ArrayList
.
Due to GitHub issue
Lombok
@Builder
is primarily meant for immutables (and uses either Collections.unmodifiableList or Guava's ImmutableList
that's why you have UnsupportedOperationException
For greater certainty reproduce full code pattern where you have exception please.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With