Replace constructor with builder
Last modified: 29 November 2022note
This refactoring is available only as an intention action.
The Replace Constructor with Builder refactoring helps hide a constructor, replacing its usages with the references to a newly generated builder class, or to an existing builder class.
Place the caret at the constructor invocation in the editor and press Alt+Enter.
From the list of available context actions, select Replace constructor with builder.
In the dialog that opens, if you need, change the suggested setter names. Specify whether you want to initialize the generated fields in the builder.
If you specify an initial value that matches the parameter value in the constructor invocation, you can skip setter method for such parameter by selecting the Optional Setter checkbox. You can also specify whether you want to create a new or use the existing builder.
Preview and apply the changes.
Example
Before
class Foo { Foo(String firstName, String lastName, int age, boolean married) {} public static void main(String[] args) { Foo joe = new Foo("Joe", "Smith", 42, false); }}
After
class Foo { Foo(String firstName, String lastName, int age, boolean married) { } public static void main(String[] args) { //married is omitted, default "false" is used Foo joe = new FooBuilder() .setFirstName("Joe") .setLastName("Smith") .setAge(42) .createFoo(); } static class FooBuilder { private String firstName; private String firstName; private int age; private boolean married; public FooBuilder setFirstName(String firstName) { this.firstName = firstName; return this; } public Foo createFoo() { return new Foo(firstName, lastName, age, married); } }}
Thanks for your feedback!