diff --git a/lombok/README.md b/lombok/README.md index a297aeb31e..34ec569e89 100644 --- a/lombok/README.md +++ b/lombok/README.md @@ -4,3 +4,4 @@ - [Using Lombok’s @Getter for Boolean Fields](https://www.baeldung.com/lombok-getter-boolean) - [Lombok @Builder with Inheritance](https://www.baeldung.com/lombok-builder-inheritance) - [Lombok Builder with Default Value](https://www.baeldung.com/lombok-builder-default-value) +- [Lombok Builder with Custom Setter](https://www.baeldung.com/lombok-builder-with-custom-setter) diff --git a/lombok/src/main/java/com/baeldung/lombok/builder/customsetter/Message.java b/lombok/src/main/java/com/baeldung/lombok/builder/customsetter/Message.java new file mode 100644 index 0000000000..95a314480f --- /dev/null +++ b/lombok/src/main/java/com/baeldung/lombok/builder/customsetter/Message.java @@ -0,0 +1,39 @@ +package com.baeldung.lombok.builder.customsetter; + +import java.io.File; +import java.util.List; + +import lombok.Builder; +import lombok.Data; + +@Builder +@Data +public class Message { + private String sender; + private String recipient; + private String text; + private File file; + + public static class MessageBuilder { + private String text; + private File file; + + public MessageBuilder text(String text) { + this.text = text; + verifyTextOrFile(); + return this; + } + + public MessageBuilder file(File file) { + this.file = file; + verifyTextOrFile(); + return this; + } + + private void verifyTextOrFile() { + if (text != null && file != null) { + throw new IllegalArgumentException("Cannot send 'text' and 'file'."); + } + } + } +} diff --git a/lombok/src/test/java/com/baeldung/lombok/builder/customsetter/BuilderWithCustomSetterUnitTest.java b/lombok/src/test/java/com/baeldung/lombok/builder/customsetter/BuilderWithCustomSetterUnitTest.java new file mode 100644 index 0000000000..3f7f276edf --- /dev/null +++ b/lombok/src/test/java/com/baeldung/lombok/builder/customsetter/BuilderWithCustomSetterUnitTest.java @@ -0,0 +1,37 @@ +package com.baeldung.lombok.builder.customsetter; + +import java.io.File; + +import org.junit.Test; + +public class BuilderWithCustomSetterUnitTest { + + @Test + public void givenBuilderWithCustomSetter_TestTextOnly() { + Message message = Message.builder() + .sender("user@somedomain.com") + .recipient("someuser@otherdomain.com") + .text("How are you today?") + .build(); + } + + @Test + public void givenBuilderWithCustomSetter_TestFileOnly() { + Message message = Message.builder() + .sender("user@somedomain.com") + .recipient("someuser@otherdomain.com") + .file(new File("/path/to/file")) + .build(); + } + + @Test(expected = IllegalArgumentException.class) + public void givenBuilderWithCustomSetter_TestTextAndFile() { + Message message = Message.builder() + .sender("user@somedomain.com") + .recipient("someuser@otherdomain.com") + .text("How are you today?") + .file(new File("/path/to/file")) + .build(); + } + +}