Eclipse code templates

Eclipse comes bundled with a nice feature in the form of editor templates. These templates allow you to quickly generate commonly used code. To use a template, simply type in the name of the template and hit Ctrl + space.

There are already a ton of templates available in vanilla Eclipse like test, which will generate a JUnit 4 test method stub, or sysout that will expand into a System.out.println();. But it is also very easy to create your own. Here I will demonstrate how by creating a code template for a SLF4J logger field.

First, open the Eclipse preferences and navigate to Java -> Editor -> Templates.
Next, press the New… button and enter the following data:

Name: logger
Context: Java
Description: new slf4j logger
Pattern:
${:import(org.slf4j.Logger, org.slf4j.LoggerFactory, java.lang.invoke.MethodHandles)}
private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.Lookup.class);

Creating an Eclipse code template
Creating an Eclipse code template

And that’s basically it. We now have created our own template for an SLF4J logger, ready to be used in our Java code.

To use our new template simply enter the name we gave it (logger) and hit Ctrl + space. Eclipse will then replace it with private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.Lookup.class); including the necessary import statements.

Invoking an Eclipse code template
Invoking an Eclipse code template
The result of the Eclipse code template
The result of the Eclipse code template