Last active
June 7, 2024 15:38
-
-
Save Hogeyama/e85c60bdfbcce993ec55a35ceaa20e25 to your computer and use it in GitHub Desktop.
Type-safe Builder in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public static class Example { | |
| private final String name; | |
| private final Integer age; | |
| private final String address; | |
| private Example(Builder<Filled, Filled> builder) { | |
| this.name = builder.name; | |
| this.age = builder.age; | |
| this.address = builder.address; | |
| } | |
| public static Builder<Required, Required> builder() { | |
| return new Builder<>(); | |
| } | |
| public static class Builder<Name, Age> { | |
| private String name; // 必須 | |
| private Integer age; // 必須 | |
| private String address; // オプショナル | |
| public Builder<Filled, Age> setName(String name) { | |
| this.name = name; | |
| return this.unsafeCast(); | |
| } | |
| public Builder<Name, Filled> setAge(Integer age) { | |
| this.age = age; | |
| return this.unsafeCast(); | |
| } | |
| public Builder<Name, Age> setAddress(String address) { | |
| this.address = address; | |
| return this.unsafeCast(); | |
| } | |
| private Builder() { | |
| } | |
| @SuppressWarnings("unchecked") | |
| private <Name_, Age_> Builder<Name_, Age_> unsafeCast() { | |
| return (Builder<Name_, Age_>) this; | |
| } | |
| } | |
| @Override | |
| public String toString() { | |
| return "Example{name='" + name + "', age=" + age + ", address='" + address + "'}"; | |
| } | |
| // メインメソッド | |
| public static void main(String[] args) { | |
| Example example = new Example(Example.builder() | |
| .setAge(30) | |
| .setName("John") | |
| .setAddress("123 Street")); | |
| System.out.println(example); | |
| } | |
| public static class Required {} | |
| public static class Filled {} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment