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

其他回答

我的良人中,有一人是弟兄。

for (${iterable_type} ${iterable_element} : ${iterable}) {
    ${cursor}
}

还有traceout,因为我经常用它来跟踪:

System.out.println("${enclosing_type}.${enclosing_method}()");

我刚刚想到了另一个,有一天在网上找到了它,const:

private static final ${type} ${name} = new ${type} ${cursor};

我喜欢这样生成类注释:

/**
 * I... 
 * 
 * $Id$
 */

“I…”立即鼓励开发人员描述类的功能。我似乎确实改善了没有文档的类的问题。

当然,$Id$是一个有用的CVS关键字。

这里有一些附加模板: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 -用MessageFormat包围选区。

 ${:import(java.text.MessageFormat)} 
 MessageFormat.format(${word_selection}, ${cursor})

这让我可以将光标移动到字符串上,将选择范围扩展到整个字符串(Shift-Alt-Up),然后按住Ctrl-Space两次。

锁定选区

锁定-环绕选定的行,最后尝试锁定。假设存在一个锁变量。

${lock}.acquire();
try {
    ${line_selection}
    ${cursor}
} finally {
    ${lock}.release();
}

注意${line_selection}模板显示在环绕菜单(Alt-Shift-Z)。

代码部分

//--------------------------------------------------------------
//                       ${title}
//--------------------------------------------------------------
${cursor}

使用此模板可以更容易地注释代码部分。它不是很复杂,但为我节省了很多时间:)