Eclipse Tips : How To Create Custom Code Template In Eclipse

One of the awesome feature in Eclipse is to create the custom code template to insert on the appropriate context. For example, there is default for loop template is exist in the Eclipse IDE, if you type for and press CTRL + SPACE, it would insert the complete for loop syntax with the condition. This eliminates the need for writing the entire block. In the same way, we can write our own custom code template for most commonly used coding techniques. In this example, I have created a custom code template for checking the null values inside the methods. Lets look the below pictures.

1. Open Templates in Eclipse

As a first step, open the templates window by navigating to Windows -> Preferences -> Java -> Editor -> Templates. This dialog box displays all the configured templates. You can edit any of the existing templates or create the new template by clicking on the “New” button. Also there is an import option for importing the available templates in a file.

Eclipse Custom Code Template 1

2. Create New Template

After you click on the “New” button, you would see the small dialog window as below. Here you have to provide the following details:

  1. Name : Name of the template. This will be displayed as the suggestions when you type CTRL + SPACE
  2. Description : This field is explanation for the template.
  3. Pattern : This is the actual template pattern that will be applied in the code. Here this template checks for the “null” value of the local variable and throws the NullPointerException if it is null.

After you fill the detail, click on the “OK” button. Your template would be saved.

Eclipse Custom Code Template 2

if (${arg:localVar} == null)
    throw new ${exception:link(NullPointerException,IllegalArgumentException)}("${arg:localVar} is null");

3. Use Custom Code Template

Now it is time for the implementation demo. Just type “null” and then press CTRL + SPACE. You would be seeing the below suggestion box which shows the custom template we have just added in the above step. Also in the right side pane it shows the actual implementation that will occur. Here the variables are substituted with actual local variables. Once you press the “Enter” key, this code will be inserted. Like this you can create more complex templates.

Eclipse Custom Code Template 3

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*