您可以在Eclipse中创建各种Java代码模板

窗口>首选项> Java >编辑器>模板

e.g.

Sysout扩展为:

System.out.println(${word_selection}${});${cursor}

您可以通过输入sysout加上CTRL+SPACE来激活它

您目前使用哪些有用的Java代码模板?包括它的名称和描述,以及为什么它很棒。

我正在寻找一个模板的原始/新颖的使用,而不是一个内置的现有功能。

创建Log4J日志记录器 从显示中获取swt颜色 Syncexec - Eclipse框架 单例模式/Enum单例生成 Readfile 常量 Traceout 格式字符串 注释代码审查 字符串格式 尝试最终锁定 消息格式i18n和log Equalsbuilder Hashcodebuilder Spring对象注入 创建FileOutputStream


当前回答

我将此用于MessageFormat(使用Java 1.4)。通过这种方式,我可以确保在进行国际化时没有难以提取的连接

i18n

String msg = "${message}";
Object[] params = {${params}};
MessageFormat.format(msg, params);

同样用于日志:

log

if(logger.isDebugEnabled()){
  String msg = "${message}"; //NLS-1
  Object[] params = {${params}};
  logger.debug(MessageFormat.format(msg, params));
}

其他回答

添加迭代Map.entrySet()的代码片段:

模板:

${:import(java.util.Map.Entry)}
for (Entry<${keyType:argType(map, 0)}, ${valueType:argType(map, 1)}> ${entry} : ${map:var(java.util.Map)}.entrySet())
{
    ${keyType} ${key} = ${entry}.getKey();
    ${valueType} ${value} = ${entry}.getValue();
    ${cursor}
}

生成的代码:

for (Entry<String, String> entry : properties.entrySet())
{
    String key = entry.getKey();
    String value = entry.getValue();
    |
}

我最喜欢的几个是……

1: Javadoc,插入关于该方法是Spring对象注入方法的文档。

 Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
* 
* @param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance 

2:调试窗口,创建FileOutputStream并将缓冲区的内容写入文件。 用于当你想要比较缓冲区与过去的运行(使用BeyondCompare),或者如果你不能查看缓冲区的内容(通过inspect),因为它太大…

java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();

静态导入Hamcrest测试

如果你想使用JUnit 4.8.2的新特性(assertThat, is, hasItems,等等…),这里有一个模板来生成带有必要hamcrest导入的@Test方法。

@${testType:newType(org.junit.Test)}
public void ${testName}() throws Exception {
    // Arrange
    ${staticImport:importStatic('org.hamcrest.MatcherAssert.*','org.hamcrest.Matchers.*')}${cursor} 
    // Act

    // Assert

}

在写测试的时候,我已经用过很多次了。

什么是安排-行动-断言?

EasyMock模板

创建模拟

${:importStatic(org.easymock.EasyMock.createMock)}
${type} ${name} = createMock(${type}.class);

重置模拟

${:importStatic(org.easymock.EasyMock.reset)}
reset(${var});

回放模拟

${:importStatic(org.easymock.EasyMock.replay)}
replay(${var});

验证模拟

${:importStatic(org.easymock.EasyMock.verify)}
verify(${var});

下面是一个foreach,用于迭代List<Stuff>。循环中的可选内容用于查找列表中的元素并返回它。

for (${t:elemType(w)} elem: ${w:collection}) {
    if (elem.get.equals(${localVar})){
        return elem;
    }
}
return null;