Merge pull request #5577 from pvangool/BAEL-2074
BAEL-2074: Lombok builder with custom setter
This commit is contained in:
commit
2c0113d073
|
@ -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)
|
||||
|
|
|
@ -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 IllegalStateException("Cannot send 'text' and '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 = IllegalStateException.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();
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue