您的位置:首页 > 编程语言 > Java开发

玩转Eclipse — 为懒人准备的Java Code Templates(持续更新中...)

2013-11-07 12:43 316 查看
        在之前的一篇博客《玩转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});


Reference

       
Useful Eclipse Java Code Templates

        玩转Eclipse — 自动代码生成的Java Code Template
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息