IntelliJ中的生成器模式代码生成 [英] Builder pattern code generation in IntelliJ

查看:115
本文介绍了IntelliJ中的生成器模式代码生成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在IntelliJ中自动编写Builder模式?

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;
   }
}

有没有一种方法可以使IDE生成以下内容或类似内容:

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;
    }
}


推荐答案

使用用Builder替换构造器重构。

要使用此功能,请在代码中单击构造函数的签名,然后右键单击并选择重构菜单,然后单击用构造函数替换构造函数...调出对话框以生成代码。

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.

这篇关于IntelliJ中的生成器模式代码生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆