Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Eclipse Code Templates

Eclipse Code Templates

Using code templates

Eclipse provides the ability to improve work efficiency and code predictability by defining and using code templates.

When developing Java programs, we often need to write the main method:



public static void main(String[]args) {



}

If we write it letter by letter, it would be a repetitive and meaningless task, so we can use Eclipse code templates to do this quickly.

We only need to type main in the class body, then use the Eclipse code assist shortcut (Alt+/ by default), and after pressing Enter, we can see that Eclipse has automatically completed the full definition of the main function:

If we want to use System.out.println(), we just need to type syso and press Alt+/:


Customizing code templates

Eclipse also provides many code templates. We can see the list of all defined code templates via Windows->Preferences->Java->Editor->Templates (you can type Templates in the search box to find it).

We select the sysout template in the popup window and click Edit on the right, which displays the following:

The editing panel is the core focus, because everything is configured here. Let's first familiarize ourselves with the five key items in this panel.

- Java type members - the code corresponding to the template is a class member; strictly speaking, the psvm template should choose this - Java statements - the code corresponding to the template is a statement block - Java - the most general, any Java code will do - Java doc - as the name implies Of course we can also define our own template variables. For example, if we define a ${myTemplateVarible}, the corresponding code will display myTemplateVarible. - ${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

For more on customizing code templates, you can click the Help Contents option in the Help menu, type "Java Editor Template Variables" in the search bar of the dialog that pops up, and select Java Editor Template Variables to view the detailed documentation: