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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020