Generate a final instance
Example 1: attributes cannot be changed
@SpringBootApplication
public class Demo12Application {
public static void main(String[] args) {
Widget testWidget = Widget.builder()
.name("foo")
.id(1)
.build();
System.out.println(testWidget.getId());
System.out.println(testWidget.getName());
}
}
@Getter
@Builder
class Widget {
private final String name;
private final int id;
}
Example 2 : @Builder(toBuilder = true) means attributes can get changed
@SpringBootApplication
public class Demo12Application {
public static void main(String[] args) {
Widget testWidget = Widget.builder()
.name("foo")
.id(1)
.build();
System.out.println(testWidget.getId());
System.out.println(testWidget.getName());
// modify attributes
testWidget = testWidget.toBuilder()
.name("OK")
.id(2)
.build();
System.out.println(testWidget.getId());
System.out.println(testWidget.getName());
}
}
@Getter
@Builder(toBuilder = true)
class Widget {
private final String name;
private final int id;
}