Reputation: 2428
I create chaned setters in classes like:
public class Example {
private String name;
private Integer id;
...
public Example withName(String name) {
this.name = name;
return this;
}
public Example withID(Integer id) {
this.id = id;
return this;
}
...
}
So initialization of instance becomes more clear (you can see the fields you've set without repetition of instance name):
Example example =
new Example()
.withName("Walter")
.withID(23);
Does intellij-idea have refactoring / code constraction methods to build chaining initialization of class automatically?
Upvotes: 2
Views: 763
Reputation: 26482
You can use Code | Generate...
to create the setters automatically. Start with adding the fields to the class:
class Example {
private String name;
private Integer id;
}
Now invoke Code | Generate...
(Cmd+N on the Mac) and select Setter
. Choose the template Builder
in the top of the dialog that appears. Select the fields you want to generate setters for and click OK
.
Result:
class Example {
private String name;
private Integer id;
public Example setName(String name) {
this.name = name;
return this;
}
public Example setId(Integer id) {
this.id = id;
return this;
}
}
If you want the setter methods to start with with
instead of set
, it is possible to modify the template.
Upvotes: 4
Reputation: 4875
Then right click select refactor and then replace the constructor with the builder.
Example e=new ExampleBuilder().setId(1).setName("name").createExample();
Upvotes: 0