Reputation: 40800
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:
(in ~/.IntelliJIdea14/config/templates/user.xml
this looks like this:)
<template name="builderMethod" value="public $CLASS_NAME$ with$VAR_GET$(final $TYPE$ $PARAM_NAME$) { this.$VAR$ = $PARAM_NAME$; return this; }" 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("this." + 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
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
IntelliJ IDEA add final to auto-generated setters
Upvotes: 3