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


当前回答

在GUI线程上调用代码

我将下面的模板绑定到快捷方式slater,以便在GUI线程上快速分派代码。

${:import(javax.swing.SwingUtilities)}
SwingUtilities.invokeLater(new Runnable() {      
      @Override
      public void run() {
        ${cursor}
      }
    });

其他回答

我经常使用这些代码段来查找空值和空字符串。

我使用“参数测试”模板作为方法中的第一个代码来检查接收到的参数。

testNullArgument

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}

您可能希望更改异常消息以符合公司或项目的标准。但是,我确实建议有一些消息,其中包括冒犯参数的名称。否则,方法的调用者将不得不查看代码以了解哪里出了问题。(一个没有消息的NullPointerException会产生一个异常,该异常具有相当无意义的消息“null”)。

testNullOrEmptyStringArgument

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument cannot be an empty string: ${varName}");
}

您还可以重用上面的空检查模板,并实现此代码片段以仅检查空字符串。然后您将使用这两个模板来生成上面的代码。

然而,上面的模板有一个问题,如果in参数是final,你将不得不修改生成的代码(${varName} = ${varName}.trim()将失败)。

如果你使用了很多final参数,想要检查空字符串,但不需要在代码中修饰它们,你可以这样做:

if (${varName} == null) {
    throw new NullPointerException(
        "Illegal argument. The argument cannot be null: ${varName}");
}
if (${varName}.trim().isEmpty()) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument cannot be an empty string: ${varName}");
}

testNullFieldState

我还创建了一些代码片段,用于检查没有作为参数发送的变量(最大的区别是异常类型,现在是IllegalStateException)。

if (${varName} == null) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field cannot be null: ${varName}");
}

testNullOrEmptyStringFieldState

if (${varName} == null) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field cannot be null: ${varName}");
}
${varName} = ${varName}.trim();
if (${varName}.isEmpty()) {
    throw new IllegalStateException(
        "Illegal state. The variable or class field " +
            "cannot be an empty string: ${varName}");
}

测试参数

这是一个测试变量的通用模板。我花了几年时间才真正学会欣赏这个,现在我经常使用它(当然是结合上面的模板!)

if (!(${varName} ${testExpression})) {
    throw new IllegalArgumentException(
        "Illegal argument. The argument ${varName} (" + ${varName} + ") " +
        "did not pass the test: ${varName} ${testExpression}");
}

你输入一个返回值的变量名或条件,后面是一个操作数("==","<",">"等)和另一个值或变量,如果测试失败,结果代码将抛出一个IllegalArgumentException。

使用稍微复杂的if子句,将整个表达式封装在“!()”中,是为了能够在异常消息中重用测试条件。

也许这会让同事感到困惑,但前提是他们必须查看代码,而如果您抛出此类异常,他们可能就不必查看代码了……

下面是一个数组的例子:

public void copy(String[] from, String[] to) {
    if (!(from.length == to.length)) {
        throw new IllegalArgumentException(
                "Illegal argument. The argument from.length (" +
                            from.length + ") " +
                "did not pass the test: from.length == to.length");
    }
}

通过调用模板,输入“from”,就可以得到这个结果。长度" [TAB] "== to.length"。

结果比“ArrayIndexOutOfBoundsException”或类似的方法更有趣,实际上可能会给用户一个机会来找出问题。

享受吧!

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

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

一种新的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);
}

我知道我是在找死,但为了完成起见,我想分享这个:

单例生成模板的正确版本,克服了有缺陷的双重检查锁定设计(上面讨论过,其他地方也提到过)

单例创建模板: 命名为createsingleton

static enum Singleton {
    INSTANCE;

    private static final ${enclosing_type} singleton = new ${enclosing_type}();

    public ${enclosing_type} getSingleton() {
        return singleton;
    }
}
${cursor}

访问使用上述方法生成的单例对象:

单例引用模板: 命名这个getsingleton:

${type} ${newName} = ${type}.Singleton.INSTANCE.getSingleton();

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

// 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);
    }
}