yankee
yankee

Reputation: 40800

How can I configure a live template that generates a builder method in IntelliJ IDEA?

I oftentimes need to create builder methods in my code. These methods are similar to getters, but they return this and they use with instead of get.

To be faster with that task I'd like to create a live-template in IDEA.

This how far I got:

configuration of the builder

(in ~/.IntelliJIdea14/config/templates/user.xml this looks like this:)

<template name="builderMethod" value="public $CLASS_NAME$ with$VAR_GET$(final $TYPE$ $PARAM_NAME$) {&#10;    this.$VAR$ = $PARAM_NAME$;&#10;    return this;&#10;}" description="create a builder method" toReformat="true" toShortenFQNames="true">
    <variable name="CLASS_NAME" expression="className()" defaultValue="" alwaysStopAt="true" />
    <variable name="VAR" expression="complete()" defaultValue="" alwaysStopAt="true" />
    <variable name="PARAM_NAME" expression="VAR" defaultValue="" alwaysStopAt="true" />
    <variable name="TYPE" expression="typeOfVariable(&quot;this.&quot; + VAR)" defaultValue="" alwaysStopAt="true" />
    <variable name="VAR_GET" expression="capitalize(VAR)" defaultValue="" alwaysStopAt="true" />
    <context>
      <option name="JAVA_EXPRESSION" value="false" />
      <option name="JAVA_DECLARATION" value="true" />
    </context>
  </template>

This nearly works, except for typeOfVariable("this." + VAR) which does not. I just guessed how to call this method, because I could not find any documentation on the syntax used in the expressions except for this page which does not even mention a script language name or something that would make googling for easier.

How do I fix the call to typeOfVariable?

Bonus question: How can I get complete() for VAR to only show fields?

Similar question but not does not even have a start: Live Template for Fluent-API Builder in IntelliJ

Upvotes: 3

Views: 3144

Answers (1)

binoternary
binoternary

Reputation: 1915

Replace typeOfVariable("this." + VAR) with typeOfVariable(VAR).

Edit:

Another way to generate builder methods is to use an appropriate setter template (instead of live template).
https://www.jetbrains.com/help/idea/2016.1/generate-setter-dialog.html

There is already a built-in setter template named "Builder" which generates setters such as:

public Foo setBar(int bar) {
  this.bar = bar;
  return this;
}

You can create your own template (e.g by copying it) and change it so that the method prefix is with.
And to make the generated method parameter final go to settings:

  • Editor | Code Style | Java
  • Select the Code Generation tab
  • Tick Make generated parameters final

IntelliJ IDEA add final to auto-generated setters

Upvotes: 3

Related Questions