Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Inserting Snippets from Code Templates

As you are typing in the Source Editor, you can use code templates to greatly speed up the entry of commonly used sequences of reserved words and common code patterns, such as for loops and field declarations. The IDE comes with a set of templates, and you can create your own.

Some code templates are composed of segments of commonly used code, such as private static final int. Others are more dynamic, generating a skeleton and then letting you easily tab through them to fill in the variable text (without having to use the mouse or arrow keys to move the cursor from blank to blank). Where a code snippet repeats an identifier (such as an Iterator object, as shown in Figure 5-4), you just have to type the identifier name once.

keegan_fig05_04.jpg

Figure 5-4 Code template with variable text to be inserted

Here are a few examples:

  • You can use the newo template to quickly create a new object instance. You type newo and a space, the IDE generates Object name = new Object(args); and highlights the two occurrences of Object. You can then type a class name and press Tab. Both occurrences of Object are changed to the class name and then args is selected. You can then fill in the parameters and press Enter to place the insertion point at the end of the inserted code.

    You can use Shift-Tab to move backward through the parameters. You can press Enter at any time to skip any parameters and jump straight to the end of the template (or where it is specified that the cursor should rest after the template's parameters are filled in).

  • You can use the fori template to create a loop for manipulating all of the elements in an array. Initially, the IDE generates the following:

     for (int i = 0; i < arr.length; i++) {
    
     }

    The index is automatically given a name that is unique within the current scope (defaulting to i). You can manually change that value (causing the IDE to change the value in all three places) or directly tab to arr, to type the array name. If an array is in scope, the IDE will use its name by default. The next time you press Tab, the cursor lands on the next line, where you can type the array processing code.

  • You can use the forc template to create a skeleton for loop that uses an Iterator object to iterate over a collection as shown in Figure 5-4.

    This code template has the additional benefit of generating an import statement for Iterator.

You can access code templates in either of the following ways:

  • Typing the first few letters of the code, pressing Ctrl-spacebar, and then selecting the template from the list in the code completion box. In the code completion box, templates are indicated with the keegan_05_02.jpg icon, as shown in Figure 5-5. The full text of the template is shown in the Javadoc box.
    keegan_fig05_05.jpg

    Figure 5-5 Code completion box and Javadoc box, with a code template selected

  • Typing the abbreviation for the code template directly in the Source Editor and then pressing the spacebar. You can find the abbreviations for the builtin Java code templates in Table 5-1. If you discover a code template in the code completion box, the abbreviation for that template is in the right column of that abbreviation's listing.

    Table 5-1. Java Code Templates in the Source Editor

    Abbreviation

    Expands To

    ab

    abstract

    bo

    boolean

    br

    break

    ca

    catch (

    cl

    class

    cn

    continue

    df

    default:

    dowhile

    do {
        ${cursor}
    } while(${condition});

    En

    Enumeration

    eq

    equals

    Ex

    Exception

    ex

    extends

    fa

    false

    fi

    final

    fy

    finally

    fl

    float

    forc

    for (Iterator it = collection.iterator(); it
    .hasNext();) {
        Object elem = (Object) it.next();
    }

    fore

    for (Iterator it = collection.iterator(); it
    .hasNext();) {
        Object elem = (Object) it.next();
    }

    fori

    for (int i = 0; i < ${arr array}.length; i++) {
    ${cursor}
    }

    ie

    interface

    ifelse

    if (${condition}) {
        ${cursor}
    } else {
    }

    im

    implements

    iof

    instanceof

    ir

    import

    le

    length

    newo

    Object name = new Object(args);

    Ob

    Object

    pst

    printStackTrace();

    pr

    private

    psf

    private static final

    psfb

    private static final boolean

    psfi

    private static final int

    psfs

    private static final String

    pe

    protected

    pu

    public

    Psf

    public static final

    Psfb

    public static final boolean

    Psfi

    public static final int

    Psfs

    public static final String

    psvm

    public static void main(String[] args) {
        ${cursor}
    }

    re

    return

    st

    static

    St

    String

    serr

    System.err.println("${cursor}");

    sout

    System.out.println("${cursor}");

    sw

    switch {

    sy

    synchronized

    tds

    Thread.dumpStack();

    tw

    throw

    twn

    throw new

    th

    throws

    trycatch

    try {
        ${cursor}
    } catch (Exception e) {
    }

    wh

    while (

    whilei

    while (it.hasNext()) {
        Object elem = (Object) it.next();
        ${cursor}
    }

If an abbreviation is the same as the text that you want to type (for example, you do not want it to be expanded into something else), press Shift-spacebar to keep it from expanding.

See Table 5-1 for a list of code templates (and their abbreviations) for Java files. The IDE also comes with sets of abbreviations for JSP files (see Chapter 8, Using Code Templates for JSP Files), XML files, and DTD files. You can create your own abbreviations for these file types and for other file types as well (such as for HTML files, SQL files, etc.).

Adding, Changing, and Removing Code Templates

The code templates that come with the IDE are representative of the kind of things you can do with code templates, but they represent only a tiny fraction of the number of potentially useful templates.

You can modify existing code templates and create entirely new ones to suit the patterns that you use frequently in your code.

To create a new code template:

  1. Choose Tools | Options, click Editor in the left panel, and select the Code Templates tab.
  2. Click New.
  3. In the New Code Template dialog box, type an abbreviation for the template and click OK.
  4. In the Expanded Text field, insert the text for the template. See Code Template Syntax below for information on how to customize the behavior of your templates.
  5. Click OK to save the template and exit the Options dialog box.

To modify a code template:

  1. Choose Tools | Options, click Editor in the left panel, and select the Code Templates tab.
  2. Select a template from the Templates table and edit its text in the Expanded Text field.
  3. Click OK to save the changes and exit the Options dialog box.

To remove a code template:

  1. Choose Tools | Options, click Editor in the left panel, and select the Code Templates tab.
  2. Select a template from the Templates table and click Remove.
  3. Click OK to save the changes and exit the Options dialog box.

Code Template Syntax

In code templates, you can set up the variable text to provide the following benefits for the template user:

  • Display a descriptive hint for remaining text that needs to be typed in.
  • Enable typing of an identifier once and have it generated in multiple places
  • Make sure that an import statement is added for a class.
  • Specify a type that a parameter of the code template is an instance of in order for the IDE to automatically generate an appropriate value for that parameter when the template is used to insert code.
  • Automatically set up a variable name for an iterator, making sure that that variable name is not already used within the current scope.
  • Set a location for the cursor to appear within the generated snippet once the static text has been generated and the variable text has been filled in.

For example, you might want to easily generate something like the following code for a class that you instantiate often:

    FileWriter filewriter = new FileWriter(outputFile);

In the definition for such a code template, you could use something like the following:

${fw type = "java.io.FileWriter"
  editable="false"} ${filewriter} = new ${fw}(${outputFile});

When the template is inserted into the code, the following things happen:

  • ${fw type = "java.io.FileWriter" editable="false"} is converted to FileWriter in the inserted code.
  • ${fw} is also converted to Filewriter (as it is essentially shorthand for the previously defined ${fw type = "java.io.FileWriter" editable="false"}).
  • ${filewriter} and ${outputFile} generate text (filewriter and outputFile, respectively).
  • filewriter is selected. You can type a new name for the field and then press Tab to select outputFile and type a name for that parameter. Then you can press Tab or Enter to place the cursor after the whole generated snippet.

You could further refine the code template by defining an instanceof attribute for ${outputFile} (e.g. OutputFile instanceof = "java.io.File"). This would enable the IDE to detect an instance of that class and dynamically insert the name of the instance variable in the generated snippet instead of merely outputFile.

See Table 5-2 for a description of examples of the syntax that you can use in the creation of code templates.

Table 5-2. Java Code Template Syntax

Syntax Element Example

Description

${}

Used to enclose dynamic parts in the template.

${ ElementName }

Text you put within the braces will appear in the generated code snippet as highlighted text that you can type over.

For example, if you use ${ Object }, that would be a hint for the template user to type in an object name.

If a given ElementName appears multiple times in the code template definition, you only have to replace the variable text once when you create a code snippet from that template.

${ ElementName type=" FULLYQUALIFIED-CLASS-NAME" editable="false"}

Includes a class name as part of the inserted code and has the IDE automatically insert an import statement for the class, if necessary.

Here, ElementName can be any unique identifier, but it is only used within the template syntax. The class referred to in FULLY-QUALIFIED-CLASS-NAME is inserted when you use the template. Specifying editable="false" merely ensures that the inserted class name is not highlighted for editing.

For example, the forc code template uses ${iter type="java.util.Iterator" editable=false} to enter Iterator into the generated code and add an import statement for that class.

${ ElementName instanceof=" FULLYQUALIFIED-CLASS-NAME"}

Declares that, if possible, the variable text that is initially generated should be the name of an instance variable of FULLY-QUALIFIED-CLASS-NAME that has been declared in the class. If there is no instance of that class available, ElementName is inserted.

This construct is used in the forc and fore templates.

${ ElementName array}

Declares that, if possible, the variable text that is initially generated should be the name of an array that is used in the class. If there is no array available within the current scope, ElementName is inserted.

This construct is used in the fori template.

${ ElementName index}

Generates a variable that is unused in the current scope, the default being i. If i is already used, then j is attempted, and then k, etc.

${cursor}

Determines where the cursor will end up after the code snippet has been inserted and all of the variable text has been filled in.

Changing the Expander Shortcut for Code Templates

If you find that the code templates get in your way because they inadvertently get invoked when you type certain strings, you can configure the IDE to activate the templates with a different key or key combination. This enables you to continue using the code template feature without having to individually change any templates that get in your way.

To change the code template expander key:

  1. Choose Tools | Options, click Editor in the left panel, and select the Code Templates tab.
  2. Select the preferred key or key combination from the Expand Template On drop-down list.
  3. Click OK to save the change and exit the Options dialog box.
  • + Share This
  • 🔖 Save To Your Account