Templates are simply "magic words" or shortcuts to standard blocks of code or text. They are very handy because once you have them setup you don't have to waste time writing boilerplate code any more! An example of a pre-defined template in Eclipse is sysout
which expands to System.out.println();
. All you have to do is type sysout
followed by Ctrl+Space
to insert the statement into your Java source file.
To see what templates are defined in Eclipse:
- Open your Preferences dialog by going to Windows > Preferences
- On the navigation tree on the left, go to Java > Editor > Templates
- You will see a list of pre-defined templates
- You can add new ones by pressing the "New..." button
General Utility Templates:
Name | if |
Context | Java statements |
Description | if null |
Pattern | |
if (${var} == null){ ${cursor} } | |
Name | if |
Context | Java statements |
Description | if not null |
Pattern | |
if (${var} != null){ ${cursor} } | |
Name | for |
Context | Java statements |
Description | iterate over map |
Pattern | |
${:import(java.util.Map.Entry)} for(Entry<${key:argType(map,0)},${value:argType(map,1)}> entry : ${map:var(java.util.Map)}.entrySet()) { ${key} key = entry.getKey(); ${value} value = entry.getValue(); ${cursor} } | |
Name | strf |
Context | Java |
Description | format string |
Pattern | |
String.format("${word_selection}${}",${var}${cursor}) | |
Name | sysf |
Context | Java statements |
Description | print formatted string to standard out |
Pattern | |
System.out.printf("${word_selection}${}",${var}${cursor}); | |
Name | static_final |
Context | Java type members |
Description | static final field |
Pattern | |
${visibility:link( public, protected, private)} static final ${type} ${NAME} = ${word_selection}${}; |
File IO Templates:
The following templates are useful for reading or writing files. They use Java 7 features such as try-with-resources to automatically close files. They also use methods from NIO2.0 to obtain a buffered reader and read the file.
Name | readfile |
Context | Java statements |
Description | read text from file |
Pattern | |
${:import(java.nio.file.Files, java.nio.file.Paths, java.nio.charset.Charset, java.io.IOException, java.io.BufferedReader)} try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}), Charset.forName("UTF-8"))) { String line = null; while ((line = in.readLine()) != null) { ${cursor} } } catch (IOException e) { // ${todo}: handle exception } | |
Name | readfile |
Context | Java statements |
Description | read all lines from file as a list |
Pattern | |
${:import(java.nio.file.Files, java.nio.file.Paths, java.nio.charset.Charset, java.util.List, java.util.ArrayList)} Lis<String> lines = new ArrayList<>(); try{ lines = Files.readAllLines(Paths.get(${fileName:var(String)}), Charset.forName("UTF-8")); }catch (IOException e) { // ${todo}: handle exception } ${cursor} | |
Name | writefile |
Context | Java statements |
Description | write text to file |
Pattern | |
${:import(java.nio.file.Files, java.nio.file.Paths, java.nio.Charset, java.io.IOException, java.io.BufferedWriter)} try (BufferedWriter out = Files.newBufferedWriter(Paths.get(${fileName:var(String)}), Charset.forName("UTF-8"))) { out.write(${string:var(String)}); out.newLine(); ${cursor} } catch (IOException e) { // ${todo}: handle exception } |
XML Templates:
The following templates are used to read xml files or strings and return a DOM.
Name | parsexml |
Context | Java statements |
Description | parse xml file as Document |
Pattern | |
${:import(org.w3c.dom.Document, javax.xml.parsers.DocumentBuilderFactory, java.io.File, java.io.IOException, javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException)} Document doc = null; try { doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new File(${filename:var(String)})); } catch (SAXException | IOException | ParserConfigurationException e) { // ${todo}: handle exception } ${cursor} | |
Name | parsexml |
Context | Java statements |
Description | parse xml string as Document |
Pattern | |
${:import(org.w3c.dom.Document, javax.xml.parsers.DocumentBuilderFactory, org.xml.sax.InputSource, java.io.StringReader, java.io.IOException, javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException)} Document doc = null; try { doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(new InputSource(new StringReader(${str:var(String)}))); } catch (SAXException | IOException | ParserConfigurationException e) { // ${todo}: handle exception } ${cursor} |
Logging Templates:
The templates below are useful for creating a logger and logging messages. I use SLF4J, but they could easily be tweaked to use any other logging framework.
Name | logger |
Context | Java type members |
Description | create new logger |
Pattern | |
${:import(org.slf4j.Logger, org.slf4j.LoggerFactory)} private static final Logger LOGGER = LoggerFactory.getLogger(${enclosing_type}.class); | |
Name | logd |
Context | Java statements |
Description | logger debug |
Pattern | |
if(LOGGER.isDebugEnabled()) LOGGER.debug(${word_selection}${}); ${cursor} | |
Name | logi |
Context | Java statements |
Description | logger info |
Pattern | |
LOGGER.info(${word_selection}${}); ${cursor} | |
Name | logerr |
Context | Java statements |
Description | logger error |
Pattern | |
LOGGER.error(${word_selection}${}, ${exception_variable_name}); | |
Name | logthrow |
Context | Java statements |
Description | log error and throw exception |
Pattern | |
LOGGER.error(${word_selection}${}, ${exception_variable_name}); throw ${exception_variable_name}; ${cursor} |
JUnit Templates:
The templates below assist in writing JUnit tests.
Name | before |
Context | Java type members |
Description | junit before method |
Pattern | |
${:import (org.junit.Before)} @Before public void setUp() { ${cursor} } | |
Name | after |
Context | Java type members |
Description | junit after method |
Pattern | |
${:import (org.junit.After)} @After public void tearDown() { ${cursor} } | |
Name | beforeclass |
Context | Java type members |
Description | junit beforeclass method |
Pattern | |
${:import (org.junit.BeforeClass)} @BeforeClass public static void oneTimeSetUp() { // one-time initialization code ${cursor} } | |
Name | afterclass |
Context | Java type members |
Description | junit afterclass method |
Pattern | |
${:import (org.junit.AfterClass)} @AfterClass public static void oneTimeTearDown() { // one-time cleanup code ${cursor} } |
Do YOU have any useful templates? If so, share them in the comments section!
Thank you!
ReplyDeleteThank you, this was quite helpful :)
ReplyDeleteJava 8? :)
ReplyDelete