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.
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:
- Name : Name of the template. This will be displayed as the suggestions when you type CTRL + SPACE
- Description : This field is explanation for the template.
- 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.
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.