A short name is easier to remember than a line of Java you keep typing. In Eclipse on Linux, you can create a Java editor template that lets Content Assist replace that name with a snippet.

The context of a template controls where Eclipse can offer it. The Java context makes the template available in Java code. A snippet that prints a line belongs inside a method.

Eclipse saves editor templates in the current workspace. When a template expands, the inserted text becomes ordinary Java source that you can edit in the file.

Steps to create a Java editor template in Eclipse:

Start with a Java source file open in Eclipse and an indented blank line inside a method. The pictures show Hello.java in the hello project in ~/eclipse-workspace.

  1. Open Window > Preferences….
  2. Enter Templates in the Preferences tree filter in place of any existing filter text.
  3. Select Templates under Java > Editor in the filtered tree.
  4. Click New… beside the Java editor templates table.
  5. Enter a short, unused name such as greetline in the Name field.
  6. Open the Context drop-down.
  7. Select Java in the Context list.
  8. Clear Automatically insert if it is checked.

    With this box clear, Eclipse offers the template for you to choose even when it is the only match.

  9. Click inside the Pattern field.
  10. Enter the following Java statement in the Pattern field.
    System.out.println("Hello");
  11. Click OK in the New Template dialog.
  12. Click Apply and Close to save the template to your workspace.
  13. Place the caret on the indented blank line inside a method in your Java file.
  14. Type your template name, greetline in this case, at the caret.
  15. Press Ctrl+Space immediately after the name to open Content Assist.
  16. Choose your template from the Content Assist list.

    When greetline is highlighted, Enter inserts that proposal.

  17. Verify that your System.out.println statement replaces the template name inside the method.
Share this guide