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


当前回答

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

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

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”或类似的方法更有趣,实际上可能会给用户一个机会来找出问题。

享受吧!

其他回答

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

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

单例创建模板: 命名为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();

日志记录器声明的模板很棒。

我还为我经常使用的日志级别创建了linfo、ldebug、lwarn和lerror。

lerror:

logger.error(${word_selection}${});${cursor}

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

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

从向量到数组

${array_type}[] ${v:var(Vector)}Array = new ${array_type}[${v}.size()];
${v}.copyInto(${v}Array);