BAEL-2074: Lombok builder with custom setter

This commit is contained in:
Paul van Gool 2018-10-30 09:36:09 -07:00
parent afc62ca73b
commit 4f84edd07a
3 changed files with 77 additions and 0 deletions

View File

@ -4,3 +4,4 @@
- [Using Lomboks @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)

View File

@ -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'.");
}
}
}
}

View File

@ -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();
}
}