Geertjan's Blog

  • November 8, 2005

Magic Multiline Code Templates in NetBeans IDE 5.0 (Part 2)

Geertjan Wielenga
Product Manager
In code templates, parameters provide the 'magic' referred to in my blog entry from yesterday. A parameter is placed within curly brackets, preceded by a dollar sign:


For example, let's take the fori code template from yesterday:

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

In this code template, you see the following parameters:

  • ${i}
  • ${arr}
  • ${cursor}

The first occurrence of a parameter can have one or more of an attribute called a hint (a hint in subsequent occurrences is ignored):

${parameter hint1=value1 hint2=value2}

So, a hint is something you tell the IDE about the kind of code that you want the template to generate. For example, in the fori code template shown above, the first occurrence of the ${i} parameter has the hint index. The parameter's name could be anything you like—${i} or ${j} or ${whatever} (except, importantly, ${cursor}, which defines the place where the IDE puts the caret after you've finished editing the parameter), but it is the hint that gives the parameter its power. Here's the list of hints that are currently available for Java source files:

  • index. Specifies that the generated value of the parameter should be an unused variable in the given context with the name 'i' (or 'j' if 'i' is used already, or 'k' if 'j' is already used, and so on).
  • array. Specifies that the generated value of the parameter should be an array variable.
  • instanceof. Specifies the parameter's instance type. For example, instanceof="java.util.Collection".

Note that, with hints, the value of the hint can be omitted—which means that the value of the hint is "true". For example ${i index} is equal to ${i index="true"}. Another noteworthy thing is that enclosing the value of the hint in quotation marks is optional too.

So, let's look at the effect of just one of these cool hints, index. Here, two things are important—if you use the index hint and the variable i is already used elsewhere in the code, fori increments i to j, and j to k, and so on:

Secondly, the starting point is always i, even if your parameter is ${a}:

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

Contrast this to not using the index hint: if you define parameter ${a}, and a is already used in the code, fori will still generate a. Also, the variable is named exactly as I've specified—${a} produces a and not i:

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

However, if the variable is already used, you will get an error when you use fori without the index hint, obviously:

Be the first to comment

Comments ( 0 )
Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.Captcha

Integrated Cloud Applications & Platform Services