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


当前回答

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

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

其他回答

slf4j日志

${imp:import(org.slf4j.Logger,org.slf4j.LoggerFactory)}

private static final Logger LOGGER = LoggerFactory
    .getLogger(${enclosing_type}.class);

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

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

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

享受吧!

这里有一些附加模板:Link I - 链接2

我喜欢这个:

readfile

 ${:import(java.io.BufferedReader,  
           java.io.FileNotFoundException,  
           java.io.FileReader,  
           java.io.IOException)}  
 BufferedReader in = null;  
 try {  
    in = new BufferedReader(new FileReader(${fileName}));  
    String line;  
    while ((line = in.readLine()) != null) {  
       ${process}  
    }  
 }  
 catch (FileNotFoundException e) {  
    logger.error(e) ;  
 }  
 catch (IOException e) {  
    logger.error(e) ;  
 } finally {  
    if(in != null) in.close();  
 }  
 ${cursor} 

更新:这个模板的Java 7版本是:

${:import(java.nio.file.Files,
          java.nio.file.Paths,
          java.nio.charset.Charset,
          java.io.IOException,
          java.io.BufferedReader)}
try (BufferedReader in = Files.newBufferedReader(Paths.get(${fileName:var(String)}),
                                                 Charset.forName("UTF-8"))) {
    String line = null;
    while ((line = in.readLine()) != null) {
        ${cursor}
    }
} catch (IOException e) {
    // ${todo}: handle exception
}

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

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

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

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