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

享受吧!

其他回答

从当前显示中获取SWT颜色:

Display.getCurrent().getSystemColor(SWT.COLOR_${cursor})

周围都是syncexec

PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable(){
    public void run(){
        ${line_selection}${cursor}
    }
});

使用单例设计模式:

/**
 * The shared instance.
 */
private static ${enclosing_type} instance = new ${enclosing_type}();

/**
 * Private constructor.
 */
private ${enclosing_type}() {
    super();
}

/**
 * Returns this shared instance.
 *
 * @returns The shared instance
 */
public static ${enclosing_type} getInstance() {
    return instance;
}

在测试代码时,我有时会错过删除一些系统。所以我给自己做了一个名为syt的模板。

System.out.println(${word_selection}${});//${todo}:remove${cursor}

在我编译之前,我总是检查我的todo,永远不会忘记删除一个系统。出来。

以下代码模板将创建记录器,并根据需要创建正确的导入。

SLF4J

${:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}
private static final Logger LOG = LoggerFactory.getLogger(${enclosing_type}.class);

Log4J 2

${:import(org.apache.logging.log4j.LogManager,org.apache.logging.log4j.Logger)} 
private static final Logger LOG = LogManager.getLogger(${enclosing_type}.class); 

Log4J

${:import(org.apache.log4j.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class);

源。

JUL

${:import(java.util.logging.Logger)}
private static final Logger LOG = Logger.getLogger(${enclosing_type}.class.getName());

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

模板:

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

它有两个陷阱:

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

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

春天注入

我知道这有点晚了,但这里是我在一个类中使用的Spring Injection:

${:import(org.springframework.beans.factory.annotation.Autowired)}
private ${class_to_inject} ${var_name};

@Autowired
public void set${class_to_inject}(${class_to_inject} ${var_name}) {
  this.${var_name} = ${var_name};
}

public ${class_to_inject} get${class_to_inject}() {
  return this.${var_name};
}