Skip to content

Commit f4b6fde

Browse files
authored
BAEL-8138: Exclude Property from Lombok @builder Annotation (#16994)
1 parent 574639a commit f4b6fde

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.lombok.builder;
2+
3+
import lombok.AllArgsConstructor;
4+
import lombok.Builder;
5+
import lombok.Data;
6+
import lombok.NoArgsConstructor;
7+
8+
@Data
9+
@NoArgsConstructor
10+
@AllArgsConstructor
11+
@Builder
12+
public class ClassWithExcludedFields {
13+
14+
private int id;
15+
private String includedField;
16+
17+
@Builder.Default
18+
private String excludedField = "Excluded Field using Default";
19+
20+
static String anotherExcludedField = "Excluded Field using static";
21+
22+
@Builder(builderMethodName = "customBuilder")
23+
public static ClassWithExcludedFields of(int id, String includedField) {
24+
ClassWithExcludedFields myObject = new ClassWithExcludedFields();
25+
myObject.setId(id);
26+
myObject.setIncludedField(includedField);
27+
28+
return myObject;
29+
}
30+
31+
}

lombok-modules/lombok/src/test/java/com/baeldung/lombok/builder/BuilderUnitTest.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,4 +40,29 @@ public void givenBuilderMethod_ClientIsBuilt() {
4040
assertThat(testImmutableClient.getName()).isEqualTo("foo");
4141
assertThat(testImmutableClient.getId()).isEqualTo(1);
4242
}
43+
44+
@Test
45+
public void whenUsingCustomBuilder_thenExcludeUnspecifiedFields() {
46+
ClassWithExcludedFields myObject = ClassWithExcludedFields.customBuilder()
47+
.id(3)
48+
.includedField("Included Field")
49+
// .excludedField() no method to set excludedField
50+
.build();
51+
52+
assertThat(myObject.getId()).isEqualTo(3);
53+
assertThat(myObject.getIncludedField()).isEqualTo("Included Field");
54+
}
55+
56+
@Test
57+
public void whenUsingBuilderDefaultAnnotation_thenExcludeField() {
58+
ClassWithExcludedFields myObject = ClassWithExcludedFields.builder()
59+
.id(3)
60+
.includedField("Included Field")
61+
.build();
62+
63+
assertThat(myObject.getId()).isEqualTo(3);
64+
assertThat(myObject.getIncludedField()).isEqualTo("Included Field");
65+
assertThat(myObject.getExcludedField()).isEqualTo("Excluded Field using Default");
66+
}
67+
4368
}

0 commit comments

Comments
 (0)