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


当前回答

在当前范围内抛出一个变量IllegalArgumentException (illarg):

throw new IllegalArgumentException(${var});

更好的

throw new IllegalArgumentException("Invalid ${var} " + ${var});  

其他回答

对于代码生产来说没什么特别的,但是对于代码审查来说非常有用

我有我的模板coderev low/med/high执行以下操作

/**
 * Code Review: Low Importance
 * 
 *
 * TODO: Insert problem with code here 
 *
 */

然后在Tasks视图中-将显示我想在会议期间提出的所有代码审查注释。

这里有一些附加模板: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
}

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

模板:

+ ", ${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};
}

我最喜欢的几个是……

1: Javadoc,插入关于该方法是Spring对象注入方法的文档。

 Method to set the <code>I${enclosing_type}</code> implementation that this class will use.
* 
* @param ${enclosing_method_arguments}<code>I${enclosing_type}</code> instance 

2:调试窗口,创建FileOutputStream并将缓冲区的内容写入文件。 用于当你想要比较缓冲区与过去的运行(使用BeyondCompare),或者如果你不能查看缓冲区的内容(通过inspect),因为它太大…

java.io.FileOutputStream fos = new java.io.FileOutputStream( new java.io.File("c:\\x.x"));
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();