Ivan Gerasimenko
Ivan Gerasimenko

Reputation: 2428

Intellij Idea automatic creation of chaining setters for class

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 have refactoring / code constraction methods to build chaining initialization of class automatically?

Upvotes: 2

Views: 763

Answers (2)

Bas Leijdekkers
Bas Leijdekkers

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

i.karayel
i.karayel

Reputation: 4875

  1. First, generate a constructor with fields.
  2. Then right click select refactor and then replace the constructor with the builder.

    Example e=new ExampleBuilder().setId(1).setName("name").createExample();
    

enter image description here

Upvotes: 0

Related Questions