How do I create and use a Java template?
Author: Deron Eriksson
Description: This tutorial describes how to create and use a Java template in Eclipse.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)

Page:    1 2 >

In another tutorial, I described what EclipseSW templates are and how to use them. I used a JSPW template as an example. In this tutorial, I'll demonstrate a JavaSW template in Eclipse. I'll use the simple Java project shown below, which contains a Test class. The project has the log4j-1.2.14.jar file in its build path.

Normally, when using log4j, you get a log4j Logger object for that class as a static member variable. We'll create a Java template to automate this task. The project is shown below, along with the Test class.

Eclipse Navigator View and Java Editor

To create a new Java template, I go to Window → Preferences → Java → Editor → Templates. I click New.

Java Templates

This brings up the New Template window. I enter the name for the new Java template, 'log'. I enter a description for the template. I also input the following Java template pattern:

	protected static Logger log = Logger.getLogger(${primary_type_name}.class);

Notice that primary_type_name is a variable that inserts the name of the current Java file's class into the variable location. For other variables that you can use, you can click the Insert Variable button. When done, I click OK.

New Template

We can see that we now have a 'log' Java template. I click OK.

Java Templates

(Continued on page 2)

Page:    1 2 >