Current Articles | RSS Feed
In my previous article, I shared a few tips to help you improve your general productivity with the Eclipse IDE. Another great productivity feature of Eclipse is its templates, which let you turn a brief snippet of code into a whole chunk. This is particularly useful when you're writing Java, with its tendency to use a certain amount of boilerplate code. Let's look at some examples of built-in templates, and see how to write your own.
Here's a quick example to try out. Open a Java code file, type syserr, and press Ctrl-Space. You'll see what you wrote magically expand to System.err.println();, with the cursor positioned between the brackets, ready to type in the string to be printed.
syserr
System.err.println();
If you go to Eclipse -> Preferences -> Java -> Editor -> Templates, you'll see a list of all of Eclipse's predefined templates. For instance, the first for template looks like this:
for
for (int ${index} = 0; ${index} < ${array}.length; ${index}++) { ${line_selection}${cursor} }
if, else, and elseif are also useful basic templates for any kind of Java code. In addition, if you select a few lines of code, then press Ctrl-Space twice, you can select one of the templates shown (if being a good example) to surround your selected code block (this is where the ${line_selection} part of the template comes in). Note that you'll need to press Ctrl-I, or Cmd-I on a Mac, afterward to sort out the indentation.
if
else
elseif
${line_selection}
But templates are even more powerful than that. Try typing for and pressing Ctrl-Space. You'll notice that the two variables (i for the iterator and array for the array to iterate over) have boxes around them. You can jump between these using the Tab key. Go to the first one, i, and edit the name you want for the iterator (or leave it if you prefer), press Tab, and you'll jump to array. Hit Tab again, and your cursor moves down, ready to fill in the body of the for block.
i
array
A whole set of predefined templates is available, and the available templates vary depending on which context (Java, JSP, Javadoc, etc.) you're in. Go to Eclipse -> Preferences -> Java -> Editor -> Templates to see them all.
Ctrl-Space isn't just useful for templates, by the way. It also autocompletes variable names and method signatures, and even tries to autocomplete CamelCase variable names from their initials. (Try IOE for IOException, for example.)
IOE
IOException
Eclipse's predefined templates are useful, but you'll often find yourself having more specific requirements for lumps of code that you use often. Happily, Eclipse allows you to create your own custom templates. Here's an example of a log template I use when writing Android code. Open the Templates window again (Eclipse -> Preferences -> Editor -> Templates) and click the New button. Give the template an abbreviation (for instance ilog) and a descriptive name, and choose the Java context. Then enter the body of the template:
ilog
Log.i(TAG, "${cursor}");
I use TAG by default as a log tag. ${cursor}, as you may be able to guess, positions the cursor between the quotes.
TAG
${cursor}
Save the template, then type ilog somewhere in your code and press Ctrl-Space to see the template do its thing.
Alternatively, instead of TAG, you could use the enclosing type name:
Log.i("${enclosing_type}", "${cursor}");
Or, instead, you could use the existing log line, but write a template to define your TAG and insert that at the top of your file:
private static final String TAG = "${enclosing_package}.${enclosing_type}";
That's useful enough, but what about an example that gives you variable names to fill in, as with the for loop? Let's try creating a template that lets you choose the log level when you fill in your template:
Log.${level}("${enclosing_type}", "${cursor}");
Here's a multiline example that I use to create a button when I'm writing Android code:
Button ${buttonname} = (Button) findViewById(R.id.${buttonid}); ${buttonname}.setOnClickListener(new OnClickListener() { public void onClick(View v) { // ${todo}: write onClick method ${cursor} { });
Here the variables buttonname and buttonid are to be filled in by the user, then the cursor jumps to the body of setOnClickListener().
buttonname
buttonid
setOnClickListener()
You'll also notice the ${todo} comment; this generates an Eclipse TODO tag. You can then go to Window -> Show View -> Tasks to see a window with all these tags. (You can of course also add TODO manually; FIXME also works, but can't be entered as a variable in a template, perhaps because it really should be used to indicate that you've found a bug, rather than that you've left a gap to fill in later!)
${todo}
TODO
FIXME
However, if you use this template in your code as-is, you'll get an error if you haven't already imported the Button and OnClickListener classes. Eclipse offers the Quick Fix (Ctrl-1) to fix this, but to save more time, you can import them by adding these lines at the top of your template:
${:import(android.widget.Button, android.view.View.OnClickListener)}
The ${:import} predefined variable imports the given classes if they have not already been imported. This saves you a lot of time you might otherwise spend pressing Ctrl-1 when adding snippets like this.
${:import}
Here are a few more useful variables:
${iterator}
$i
$j
${return_type}
${array}
${array_element}
${array_type}
for (int ${index} = 0; ${index} < ${array}.length; ${index}++) { ${array_type} ${array_element} = ${array}[${index}]; ${cursor} }
String[] stringArray = {"foo", "bar"};
for (int i = 0; i < stringArray.length; i++) { String string = stringArray[i]; }
with the cursor positioned appropriately. For the given array, the array type and a new local array element have been correctly generated.
${iterable}
${iterable_type}
${iterable_element}
foreach
Set<MyObject> set = someObject.getSet();
for (MyObject object : set) { }
When creating your own templates, note that you can specify whether the template should be automatically inserted if there is only one possible match when you press Ctrl-Space. Otherwise, even if there's only one option, you'll still be presented with a drop-down box to confirm it.
Templates revolutionized my Java coding with Eclipse; learning to harness the power of even just the built-in templates can help you too get your Java coding up to light speed!
Allowed tags: <a> link, <b> bold, <i> italics