Search code examples
javaintellij-ideaconstructorcode-generation

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:

  • Mark them final.
  • Append Arg to the end of each variable name.
    For example, firstNameArg & lastNameArg rather than firstName & lastName.
  • Annotate each argument with @NotNull.

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.


Solution

  • 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.