Eclipse Custom Variable for Java Code Templates

By | January 12, 2018
Questions:

How do you add a new variable to be inserted into a Java code template. How do I add a variable to the list in Window->Preferences->Java->Code Style->Code Templates->Code->New Java Files->Edit->Insert Variable… ?

Currently my new files get created with:

${filecomment}
${package_declaration}
${typecomment}
${type_declaration}

I’d like them to get created with something like:

${begin_filecomment}
${package_declaration}
${typecomment}
${type_declaration}
${end_filecomment}

where begin_filecomment and end_filecomment appear in the Insert Variable list.

Answers:

I’m pretty sure that the list of “variables” is generated by Eclipse and there is no way to add a new template variable.

What do you want ${begin_filecomment} and ${end_filecomment} to be? Just type the content into the Edit box – there is nothing that says you cannot put static content in there.

Questions:
Answers:

Yes, you can indeed add a variable to this list. See the extension point called

org.eclipse.ui.editors.templates

and you’ll find out how.

Questions:
Answers:

To contribute a new variable, you need to create a plugin and implement the org.eclipse.ui.editors.templates extension-point.

You have to contribute a sub-class of org.eclipse.jface.text.templates.TemplateVariableResolver that will implement the various resolve methods to resolve the placeholder to your desired value(s).

See here for help on the extension point and an example that contributes the ant variables.

As matt b says, you often just need to define your text as boilerplate, so implementing a variable for that is overkill.

Questions:
Answers:

and see http://ahoehma.wordpress.com/2009/08/24/use-maven-artifact-version-in-eclipse-templates/

Questions:
Answers:

I didn’t try it, but maybe you could edit the template files in the JDT jar:

eclipse\plugins\org.eclipse.jdt.ui_*.jar\templates\

Questions:
Answers:

See
http://thomaswabner.wordpress.com/2009/08/21/use-your-own-variable-in-eclipse-code-templates/

Questions:
Answers:

To add on to the conversation, I also wanted to insert a custom variable into a template. My issue was that I wanted to insert a variable from jsp/jstl definition inside the template.

(I.E. <c:set var="myVariable" value="${requestScope.variableName}" />)

This apparently caused some issues because templates already use the ${} syntax to help resolve its own variables.

So simple solution I included an additional $ to the pattern in the template. Two $$ signs resolves it to a single $ sign, hence giving me exactly what I wanted. Hopefully this helps the poster or someone with similar situation.

Leave a Reply

Your email address will not be published. Required fields are marked *