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


当前回答

我喜欢这样生成类注释:

/**
 * I... 
 * 
 * $Id$
 */

“I…”立即鼓励开发人员描述类的功能。我似乎确实改善了没有文档的类的问题。

当然,$Id$是一个有用的CVS关键字。

其他回答

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

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

下面是一个非实例化类的构造函数:

// Suppress default constructor for noninstantiability
@SuppressWarnings("unused")
private ${enclosing_type}() {
    throw new AssertionError();
}

这个是针对自定义异常的:

/**
 * ${cursor}TODO Auto-generated Exception
 */
public class ${Name}Exception extends Exception {
    /**
     * TODO Auto-generated Default Serial Version UID
     */
    private static final long serialVersionUID = 1L;    

    /**
     * @see Exception#Exception()
     */
    public ${Name}Exception() {
        super();
    }

    /**
     * @see Exception#Exception(String) 
     */
    public ${Name}Exception(String message) {
        super(message);         
    }

    /**
     * @see Exception#Exception(Throwable)
     */
    public ${Name}Exception(Throwable cause) {
        super(cause);           
    }

    /**
     * @see Exception#Exception(String, Throwable)
     */
    public ${Name}Exception(String message, Throwable cause) {
        super(message, cause);
    }
}

我将此用于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));
}

一种新的JUnit测试方法:

 @${testType:newType(org.junit.Test)}
 public void ${testname}() throws Exception {
     ${staticImport:importStatic('org.junit.Assert.*')}${cursor}

     String expected = "" ;
     String actual = "" ;

     Assert.assertEquals(expected, actual);
}

格式化字符串

MessageFormat -用MessageFormat包围选区。

 ${:import(java.text.MessageFormat)} 
 MessageFormat.format(${word_selection}, ${cursor})

这让我可以将光标移动到字符串上,将选择范围扩展到整个字符串(Shift-Alt-Up),然后按住Ctrl-Space两次。

锁定选区

锁定-环绕选定的行,最后尝试锁定。假设存在一个锁变量。

${lock}.acquire();
try {
    ${line_selection}
    ${cursor}
} finally {
    ${lock}.release();
}

注意${line_selection}模板显示在环绕菜单(Alt-Shift-Z)。