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


当前回答

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

其他回答

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

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

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

从向量到数组

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

我看到了一个创建基本测试类的模板的答案,如果你更喜欢这种方法,这里有一些单独的调用:

使用@Before import创建setUp方法

${:import(org.junit.Before)}
@Before
public final void setUp() {
  ${cursor}
}

使用@Test import创建新的测试方法

${:import(org.junit.Test)}
@Test
public final void test${newName} () {
${cursor}
}

我使用以下代码来帮助在类型和dto之间进行JAXB转换:

将现有变量转换为返回值类型的模板(与形参一起使用)

${return_type} ${name} = null;

if (${var} != null) {
    ${name} = new ${return_type}();
    ${cursor}
}
return ${name};

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

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

lerror:

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

我使用以下模板进行Android开发:

详细(日志)

Log.v(TAG, ${word_selection}${});${cursor}

调试(Logd)

Log.d(TAG, ${word_selection}${});${cursor}

(信息的人类学)

Log.i(TAG, ${word_selection}${});${cursor}

Warn (Logw)

Log.w(TAG, ${word_selection}${});${cursor}

错误(包厢)

Log.e(TAG, ${word_selection}${});${cursor}

Assert (Loga)

Log.a(TAG, ${word_selection}${});${cursor}

TAG是我在每个活动中定义的常量。