More about faster Java coding in Eclipse Galileo

Using code templates


The problems

Regardless of your project or team size, two problems occur when you edit the code base:

  • Lack of consistency— When many people on a team edit files, small differences in coding can creep in and make the code more difficult to understand and maintain. It's more difficult to search for occurrences of code if they differ. Even if you work by yourself, differences can occur from day to day if you forget how you previously wrote a piece of code.
  • Lack of productivity— Saving keystrokes saves time because typing is at the heart of editing code. Larger sections of code may take some time to type or even to copy, paste, and change to fit the current context.

Before templates, a common but manual way of closing the gaps of consistency and productivity was to copy and paste. You search your existing code base — or the Internet — and copy the code that is closest to what you want to do. Then you change the parts that apply to your application.

The solution: Using templates

Templates in Eclipse are predefined listings of code that contain a section of code that doesn't change between uses. For instance, a for loop in Java™ code is constructed the same way no matter where it's used, except the inside condition or variables for the loop change. A template contains the parts that stay the same and uses variables for the parts that change.

Using templates in Eclipse is a great way to solve problems of consistency and productivity. With a template, you can write the code once and use it throughout your application with confidence. Or you might not even think about it, which is also the point.

This article explains how to:

  • Invoke templates
  • Edit templates
  • Create templates
  • Take advantage of variables in templates
  • Export templates
  • Import templates

Invoking a template

Invoking a template is easy. While typing in the editor, start typing the template name and use Ctrl+Space to invoke the code completion. The templates with names that match what you typed appear in the list (see Figure 1).

Figure 1. Choosing the template from the list
Figure 1 shows that the templates with names that match what you typed appear in the list
Figure 1 shows that the templates with names that match what you typed appear in the list

If you press Ctrl+Space again, Eclipse continues to cycle through the types of templates.

To insert a template, use the arrow keys to select the template from the list and press Enter. Alternatively, you can use the mouse to double-click on the name of the template in the list.

When the template is inserted, you have a chance to type in the values for the variables. Use the Tab key to move from variable to variable.

Editing a template

To edit a template, open the Eclipse Preferences by selecting Window > Preferences. Go to Java > Editor > Templates to see the existing templates. To edit an existing template, click on it in the list and click Edit. The Edit Template window appears (see Figure 2).

Figure 2. Editing the template
Figure 2 shows that the Edit Template window appears
Figure 2 shows that the Edit Template window appears

Table 1 describes the fields in the Edit Template window.

Table 1. Field descriptions for the Edit Template window
NameThe name of the template.
ContextThe context of the template. Eclipse limits the template choices to ones that are valid for the context. For instance, Java statements don't appear when you are editing XML files.
Automatically insertWhen selected, Eclipse automatically inserts the template if the full name of the template is typed and the template insertion is invoked (for instance, with Ctrl+Space).
DescriptionDescribes the template and is displayed in the drop-down list. The description helps identify the template because the name does not have to be unique.
PatternThe actual code that is inserted as the template, including any variables you want Eclipse to resolve.

You can edit the values for the template, and when you're done, click OK. To insert a built-in variable while you're editing the template, click Insert Variable. See "Taking advantage of variables in templates" to learn more about the variables available to you.

Creating a template

To create a template, click New. Edit the values as explained in "Editing a template," and when you're done, click OK. The new template now appears in the list. Click OK when you're done to edit your files.

Taking advantage of variables in templates

One of the largest challenges of using templates is knowing what the built-in variables resolve to when inserted into the code. These variables can automatically insert things like the name of the current type, location of the cursor, or selected values. The variables allow your templates to be much more dynamic and decrease the amount of manual changes you need to make to the template after it's inserted.

Consider the template code in Listing 1.

Listing 1. The template for a logging declaration
private static Logger logger = Logger.getLogger(${enclosing_type}.class.getName());

When inserted into the Automobile class, the code looks like Listing 2.

Listing 2. The Automobile class after the logging declaration is inserted
private static Logger logger = Logger.getLogger(Automobile.class.getName());

You can see that the name of the class is resolved for you. This is better than the copy-and-paste technique where you can forget to update the name of the class. Because the incorrect class name in the declaration won't throw a compile error, you're likely to miss it until you're looking at the logs and wondering why the statements aren't where you expect them to be.

The import statement for the Logger is also automatically added for Logger at the top of the class.

Table 2 lists and describes the built-in variables that come with Eclipse for Java templates.

Table 2. Eclipse's built-in variables for Java templates
cursorPlaces the editor's cursor in this location.N/A
dateInserts the current date.Oct 20, 2009
dollarInserts the literal dollar sign.$
elemTypeTries to guess the type of the element with the given ID.MyType
enclosing_methodInserts the name of the method that the template is being inserted into.method()
enclosing_method_argumentsInserts the arguments for the surrounding method.arg1, arg2
enclosing_packageInserts the name of the current class's
enclosing_projectInserts the name of the project that contains the class being edited.myProject
enclosing_typeInserts the name of the type (class) being edited.MyType
exception_variable_nameInserts an exception variable name, making a best guess.e, ioe
fileThe short name of the
importInserts an import statement for the given type, if it's not already imported.import com.example.ui.MyOtherType
importStaticThe same as import, but with static imports.import static com.example.ui.MyOtherType.*
line_selectionInserts the selected lines in the location. Useful for wrapping lines with, while loop with selected lines as body
primary_type_nameShort name of the file without the extension.MyType
timeInserts the current time.9:09:35 a.m.
todoThe TODO tag in comments.TODO
userThe current user name.ngood
varResolves to local variables, providing a list if there is more than one.myvar
word_selectionInserts the currently selected word.N/A
yearInserts the current year into the code.2009

Another great feature of variables is that you can make up your own. They will not automatically resolve to any values. However, right after the template is inserted, you can type values into the template. When you type into a variable, the value you type is inserted wherever the variable is present in the code. Consider the template in Listing 3.

Listing 3. Creating your own variables
public void test${my_variable}() {
    String expected = "value";
    assertEquals("${message}", expected, ${my_object}.get${my_variable});

When you insert the template, it looks like Figure 3.

Figure 3. Automatically inserting the values
Screenshot showing automatically inserting the values
Screenshot showing automatically inserting the values

All you have to do is type in the first value, and the rest are automatically replaced. When you're done, press Tab to move to the next variable.

Exporting templates

To share your templates with other users, you can export them to a file. The file is an XML file that contains the template information and can be imported into other instances of Eclipse.

To export a template, select the template and click Export. Eclipse prompts you for a location where you can save the file. When you finish exporting the templates, click OK to close the Preferences window.

Importing templates

You can import templates from a file that contains exported templates. To import a template, click Import. Eclipse prompts you for a file to import.

After you import the templates you want, click OK. You can now insert the new templates into your editor.


Code templates in Eclipse are a way to increase productivity and consistency in your applications. You can build code templates you can use to easily insert commonly used sections into your code while you're editing it. You can define variables in the code to automatically insert names of types, methods, or even selected code into your templates. When you have templates that you like, you can share them by exporting them and importing them into Eclipse.

Downloadable resources

Related topics


Sign in or register to add and subscribe to comments.

Zone=Open source
ArticleTitle=More about faster Java coding in Eclipse Galileo