design-patternsintellij-ideacode-generationbuilder-pattern

Builder pattern code generation in IntelliJ


Is there any way to automate writing Builder patterns in IntelliJ?

For example, given this simple class:

class Film {
   private String title;
   private int length;

   public void setTitle(String title) {
       this.title = title;
   }

   public String getTitle() {
       return this.title;
   }

   public void setLength(int length) {
       this.length = length;
   }

   public int getLength() {
       return this.length;
   }
}

is there a way that I could get the IDE to generate this, or similar:

public class FilmBuilder {

    Film film;

    public FilmBuilder() {
        film = new Film();
    }

    public FilmBuilder withTitle(String title) {
        film.setTitle(title);
        return this;
    }

    public FilmBuilder withLength(int length) {
        film.setLength(length);
        return this;
    }

    public Film build() {
        return film;
    }
}

Solution

  • Use the Replace Constructor with Builder refactoring.

    To use this function, click on the constructor's signature in your code, then right click and select the "Refactor" menu, then click "Replace Constructor with Builder..." to bring up the dialog box to generate the code.