provides software and services that enable enterprises
Live Chat 1-888-673-6564

Open Source Software Technical Articles

  • Home
  • Search
  • Contact Us
  • Products and Support
  • Services
  • Enterprise OSS Blog
  • Wazi Technical Blog
  • About Wazi
  • Attributions and Licensing
  • Supply Chain Compliance
  • How to Contribute
  • Contributors
  • Resources Library
  • Cloud Services
  • Partners
  • Customers
  • Community
  • Company
  • Careers
  • News and Events

Subscribe to Wazi by Email

Your email:


Enterprise Developer Support 24 x 7, Get a Support Quote Now!


click-here-to-chat-with-an-online-representative

download-oss-discovery

Latest Posts

  • Use Perl to enhance ModSecurity
  • The secret to great reporting with Drupal 7
  • A more colorful LibreOffice unveiled
  • Toward a more colorful LibreOffice
  • Flexible administration with Puppet's Facter and templates
  • Knock for OpenSSH
  • Get more out of phpMyAdmin
  • Image annotation in GIMP, Dia, and OpenOffice Draw
  • Solr, Drupal 7, and faceted search
  • Using FreeNAS' new full disk encryption for ZFS

Connect with Us!

Current Articles | RSS Feed RSS Feed

Improve your productivity with Eclipse templates

Posted by Juliet Kemp on Thu, Sep 20, 2012
  
Email This Email Article  
Tweet  
  

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.

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 (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.

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.

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.)

Create your own templates

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:

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.

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}";

Custom templates with variables

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().

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!)

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.

More useful template variables

Here are a few more useful variables:

  • ${iterator} evaluates to the first unused iterator local variable name: $i, then $j, etc. Note that you can still override this variable name when the code is entered.
  • ${return_type} evaluates to the return type of the enclosing method.
  • ${array}, ${array_element}, and ${array_type} are is useful when you've created an array already. For example, there is a second fortemplate that looks like this:
     for (int ${index} = 0; ${index} < ${array}.length; ${index}++) {
      ${array_type} ${array_element} = ${array}[${index}];
      ${cursor}
    }
    
    If you create a String array with this line:
     String[] stringArray = {"foo", "bar"};
    then type for, press Ctrl-Space, and choose the second option, you get this code:
    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.

  • Similarly, you can use ${iterable}, ${iterable_type}, and ${iterable_element}, as shown in the built-in foreachtemplate. First, create a local variable which is an iterable object:
    Set<MyObject> set = someObject.getSet();
    On the next line, type foreach and press Ctrl-Space, then select the foreachtemplate. This automatically picks up the iterable Set in the previous line, and generates code that looks like this:
     for (MyObject object : set) {
      			
    }
    with the cursor positioned between the brackets. This even works a few lines down the method, as it operates on the most recently identified iterable.

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!

Follow @openlogic
Follow @OSCloudServices

This work is licensed under a Creative Commons Attribution 3.0 Unported License
Creative Commons License.
Tags: Eclipse, Tips & Tricks

Comments

Currently, there are no comments. Be the first to post one!
Post Comment
Name
 *
Email
 *
Website (optional)
Comment
 *

Allowed tags: <a> link, <b> bold, <i> italics

Loading...
Error sending email
Email sent successfully

Email article
Email To : 
Your name : 
Message : (maximum 200 characters)
Home | Search | Contact Us | Products and Support | Services | Enterprise OSS Blog | Wazi Technical Blog | Resources Library | Cloud Services | Partners | Customers | Community | Company | Careers | News and Events
Products
OpenLogic Exchange (OLEX)
License Compliance Module
OSS Discovery
OSS Deep Discovery
OpenUpdate
Services
Open Source Support
CentOS Support
Scanning & Compliance
Open Source Training
Professional Services
Solutions
Support & Indemnification
Open Source Governance
Open Source Scanning
Open Source Provisioning
Consulting & Training
Contact Us
1-888-673-6564


© 2013 OpenLogic, Inc. All rights reserved.
Site Map  |  Privacy Policy