您可以在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


当前回答

对于log,在成员变量中添加一个有用的小调。

private static Log log = LogFactory.getLog(${enclosing_type}.class);

其他回答

这里有更多的模板。

包括:

从特定的日期创建一个日期对象 创建一个新的泛型数组列表 日志设置 指定级别的日志 创建一个新的通用HashMap 遍历映射,打印键和值 使用SimpleDateFormat解析时间 逐行读取文件 记录并重新抛出捕获的异常 打印代码块的执行时间 创建定时定时器 将字符串写入文件

静态导入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

}

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

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

这省去了大量打印/记录本地值的繁琐工作。它自动捕获字符串中的变量名。这节省了大量的打字和错字改正。

模板:

+ ", ${1:var}: " + ${1:var}

它有两个陷阱:

尽管会提示您选择一个本地/参数/字段,但这并不包括原语:(

只要编译代码时没有错误,就会出现大多数提示。使用这个宏通常会导致语法暂时被破坏,因此需要使用一些杂耍来插入多个变量。没有什么比在变量名中没有错别字更方便的了。

Bean属性

private ${Type} ${property};

public ${Type} get${Property}() {
    return ${property};
}

public void set${Property}(${Type} ${property}) {
    ${propertyChangeSupport}.firePropertyChange("${property}", this.${property},     this.${property} = ${property});
}

PropertyChangeSupport

private PropertyChangeSupport ${propertyChangeSupport} = new PropertyChangeSupport(this);${:import(java.beans.PropertyChangeSupport,java.beans.PropertyChangeListener)}
public void addPropertyChangeListener(PropertyChangeListener listener) {
  ${propertyChangeSupport}.addPropertyChangeListener(listener);
}

public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  ${propertyChangeSupport}.addPropertyChangeListener(propertyName, listener);
}

public void removePropertyChangeListener(PropertyChangeListener listener) {
  ${propertyChangeSupport}.removePropertyChangeListener(listener);
}

public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) {
  ${propertyChangeSupport}.removePropertyChangeListener(propertyName, listener);
}

添加迭代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();
    |
}