Eclipse Code Templates
Using Code Templates
Eclipse offers the capability to enhance productivity and code predictability by defining and utilizing code templates.
When developing Java programs, we often need to write the main method:
public static void main(String[] args) {
}
Typing it letter by letter would be repetitive and meaningless. Instead, we can use Eclipse code templates to quickly accomplish this task.
Simply type main
within the class body and use Eclipse's code assist shortcut (default is Alt+/). Press Enter, and Eclipse will automatically complete the full definition of the main function:
If we want to use System.out.println()
, we just need to type syso
and then press Alt+/:
Customizing Code Templates
Eclipse provides many code templates. You can view all predefined templates by navigating to Windows->Preferences->Java->Editor->Templates (you can search for "Templates" in the search box).
Select the sysout
template in the popup window and click Edit on the right, which displays:
The edit panel is the focal point as all configurations are done here. Let's familiarize ourselves with the five key elements in this panel:
- Name: The name, which is the code abbreviation you can use later.
- Context: The template context, specifying where the code template is effective. For Java, it includes at least these four:
- Java type members, where the template corresponds to class members;
psvm
should strictly choose this. - Java statements, where the template corresponds to statement blocks.
- Java, the most general, valid for any Java code.
- Java doc, as the name implies.
- Java type members, where the template corresponds to class members;
- Template Variables: Eclipse has preset some template variables (click Insert Variables to see all preset variables), such as:
${cursor}
represents the cursor.${date}
represents the current date string.${time}
represents the current time string.${line_selection}
selects the current line.${word_selection}
selects the current word.
- Pattern: The pattern corresponding to the code template, input it as you would like the code to be formatted.
For more details on customizing code templates, you can click on the Help menu, select Help Contents, and in the dialog box, search for "Java Editor Template Variables" and choose Java Editor Template Variables to view the specific documentation.