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


当前回答

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

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

其他回答

List_methods——为列表生成添加、删除、计数和包含的方法

public void add${listname}(${listtype} toAdd){
    get${listname}s().add(toAdd);
}

public void remove${listname}(${listtype} toRemove){
    get${listname}s().remove(toRemove);
}

public ${listtype} get${listname}(int index){
    return get${listname}s().get(index);
}

public int get${listname}Count(){
    return get${listname}s().size();
}

public boolean contains${listname}(${listtype} toFind){
    return get${listname}s().contains(toFind);
}

${cursor}

id——为简单的JPA @Id插入注释、导入、字段和getter

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

public Long getId(){
    return id;
}

${cursor}
${:import (javax.persistence.GenerationType,javax.persistence.GeneratedValue,javax.persistence.Id)}

我最喜欢的几个是……

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();

strf ->字符串。Format ("msg", args)非常简单,但节省了一些输入。

String.format("${cursor}",)

我刚刚注意到@邓肯琼斯已经有这个模板,但添加${line_selection}和使用Shift + Alt + Z是一个有用的策略。

这可能只是我正在从事的项目中一些糟糕设计的一点hack fix,但我有很多情况下,一些遗留代码正在修改AWT线程之外的Swing组件,并导致间歇性错误,所以为了快速修补这些问题,我使用:

${:import(javax.swing.SwingUtilities)}
// Ensure that any Swing components will be invoked only from the AWT thread
SwingUtilities.invokeLater(new Runnable() {

    @Override
    public void run() {
        ${line_selection}${cursor}
    }
});

因此,我可以突出显示违规语句,并使用Shift + Alt + Z环绕。我把这个模板称为swinvoke。

Null检查!

if( ${word_selection} != null ){
    ${cursor}
}

if( ${word_selection} == null ){
    ${cursor}
}