在之前的一篇博客《玩轉Eclipse — 自動代碼生成的Java Code Template》中詳細介紹了,如何利用Java Code Template自動地快速生成具有一定規律、可以模板化的代碼。一個簡單的Content Assist快捷鍵,就可以幫助我們生成很長的一段代碼,避免重複地敲相同代碼,同時保證相同代碼格式相同,提高軟件開發的效率。本文結合自己工作中的實踐,收集了一些常用的Code Template,分享給想使自己編碼速度更快的朋友。如果後面發現更多好的Code Template,會不斷更新到該博客中。
1. 自己收集的Template
- Const屬性
private static final ${type} ${name} = new ${type}(${cursor});
- Format字符串
${:import(java.text.MessageFormat)}
MessageFormat.format(${word_selection}, ${cursor});
- SLF4J日誌
${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
/**
* Logging mechanism.
*/
private static Logger logger = LoggerFactory.getLogger(${enclosing_type}.class);
- Singleton模式
/**
* The shared instance.
*/
private static ${enclosing_type} instance = new ${enclosing_type}();
/**
* Private constructor.
*/
private ${enclosing_type}() {
super();
}
/**
* Returns this shared instance.
*
* @returns The shared instance
*/
public static ${enclosing_type} getInstance() {
return instance;
}
- 讀取文件
${:import(java.io.BufferedReader,
java.io.FileNotFoundException,
java.io.FileReader,
java.io.IOException)}
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(${fileName}));
String line;
while ((line = in.readLine()) != null) {
${cursor}
}
}
catch (FileNotFoundException e) {
// Handle exception
}
catch (IOException e) {
// Handle exception
} finally {
if(in != null) in.close();
}
- TestNG測試方法
${:import(org.testng.annotations.Test, org.testng.annotations.Parameters, org.testng.Assert)}
@Test(groups = "${name}")
public final void ${name}() {
${cursor}
}
2. Eclipse內置的Template
- syserr:print to standard error
System.err.println(${word_selection}${});${cursor}
- sysout:print to standard out
System.out.println(${word_selection}${});${cursor}
- systrace:print current method to standard out
System.out.println("${enclosing_type}.${enclosing_method}()");
- cast:dynamic cast
${type} ${new_name} = (${type}) ${name};
- do:do while statement
do {
${line_selection}${cursor}
} while (${condition:var(boolean)});
- foreach:iterate over an array or Iterable
for (${iterable_type} ${iterable_element} : ${iterable}) {
${cursor}
}
- ifelse:if else statement
if (${condition:var(boolean)}) {
${cursor}
} else {
}
- switch:switch case statement
switch (${key}) {
case ${value}:
${cursor}
break;
default:
break;
}
- main:main method
public static void main(String[] args) {
${cursor}
}
- new:create new object
${type} ${name} = new ${type}(${arguments});