Basil Bourque
Basil Bourque

Reputation: 338316

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

I would like to customize the naming of the arguments generated by IntelliJ 2017.2 when choosing Code > Generate > Constructor to:

Is there some way to customize the generation of constructor code?

This Question, Customizing of code generation in IntelliJ IDEA, is similar but (a) does not refer to Constructor, and (b) may be outdated.

Upvotes: 5

Views: 2636

Answers (1)

glytching
glytching

Reputation: 47865

I don't think IntelliJ provides this OOTB. You could, perhaps, use a Live Template via Preferences > Editor > Live Templates.

Template text:

private final $parameterType$ $parameterName$;

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

Change the "Applicability" of the Live Template to be:

  • Java > Declaration
  • Java > Smart type completion

Click on Edit variables and set the Expression associated with each of the variables as follows:

  • parameterType: completeSmart()
  • parameterName: suggestVariableName()
  • constructorClass: className()
  • parameterNameSuffix: camelCase(String)

Here are some screenshots showing it in action:

enter image description here

enter image description here

enter image description here

enter image description here

However, this approach has some caveats (some of which may be deal breakers for your use case):

  • It cannot be applied to a pre existing class i.e. it cannot interrogate a class, find its members and generate a constructor from those. Instead, it is a way of triggering declaration of class members and it creates a constructor on-the-fly as you declare the class members.
  • If you want it to support multiple class members / constructor parameters then you'll probably have to create a live template for a single arg constructor and then copy that for a two-arg constructor and again for a three-arg constructor etc.

Upvotes: 3

Related Questions