在 IntelliJ 中自定义 `Code` > `Generate` > `Constructor`

Customize `Code` > `Generate` > `Constructor` in IntelliJ

我想在选择 Code > Generate > Constructor 时自定义 IntelliJ 2017.2 生成的参数的命名:

有什么方法可以自定义构造函数代码的生成吗?

这个问题 Customizing of code generation in IntelliJ IDEA 很相似,但 (a) 不涉及构造函数,并且 (b) 可能已过时。

我认为 IntelliJ 不提供这种 OOTB。也许,您可以通过 Preferences > Editor > Live Templates.

使用 Live Template

模板文本:

private final $parameterType$ $parameterName$;

public $constructorClass$(final $parameterType$ $parameterName$$parameterNameSuffix$){
    this.$parameterName$ = $parameterName$$parameterNameSuffix$;
}

将实时模板的 "Applicability" 更改为:

  • Java > Declaration
  • Java > Smart type completion

单击 Edit variables 并设置与每个变量关联的 Expression,如下所示:

  • 参数类型:completeSmart()
  • 参数名:建议变量名()
  • 构造函数类:class名称()
  • parameterNameSuffix: camelCase(String)

以下是一些实际使用中的屏幕截图:

但是,这种方法有一些注意事项(其中一些可能会破坏您的用例):

  • 它不能应用于预先存在的 class 即它不能询问 class,找到它的成员并从中生成构造函数。相反,它是一种触发 class 成员声明的方式,它会在您声明 class 成员时即时创建一个构造函数。
  • 如果您希望它支持多个 class 成员/构造函数参数,那么您可能必须为单个 arg 构造函数创建一个实时模板,然后将其复制到一个双参数构造函数,然后再次复制三参数构造函数等