Eclipse Template(代碼模板)是預定義的代碼片段,通過快捷鍵(默認 Ctrl+Space)快速展開,極大提升編碼速度並保證風格統一。配置路徑:Window → Preferences → Java → Editor → Templates。
名稱:sysout(覆蓋默認)
模式:
System.out.println("${name}:\t" + ${name});
效果:輸入 sysout + 回車,光標自動定位到 ${name},輸入變量名如 userCount,生成:
System.out.println("userCount:\t" + userCount);
提示:生產環境建議使用 SLF4J/Log4j,可另建 logd、logi 等日志模板。
名稱:fora (for array)
模式:
for (int ${index} = 0, length = ${array}.length; ${index} < length; ${index}++) {
${line_selection}${cursor}
}
優勢:將 .length 提取到局部變量,避免每次循環訪問數組屬性(雖然 JIT 會優化,但寫法更規範)。
變量說明:${index} 循環變量名,${array} 數組變量名,${line_selection} 選中代碼填充循環體,${cursor} 最後光標位置。
名稱:forar (for array reverse)
模式:
for (int ${index} = ${array}.length - 1; ${index} >= 0; ${index}--) {
${line_selection}${cursor}
}
場景:刪除集合元素、逆序處理、棧式邏輯。
| 名稱 | 用途 | 模式片段 |
|---|---|---|
| try-catch | 快速包裹異常 | try { ${line_selection}${cursor} } catch (${Exception} e) { e.printStackTrace(); } |
| singleton | 單例模式 | private static ${class_name} instance = new ${class_name}(); private ${class_name}() {} public static ${class_name} getInstance() { return instance; } |
| newlist | ArrayList 實例化 | List<${type}> ${name} = new ArrayList<>(); |
| newmap | HashMap 實例化 | Map<${key}, ${value}> ${name} = new HashMap<>(); |
${cursor}:展開後光標最終位置${line_selection}:當前選中的行內容(用於包裹模式)${word_selection}:當前選中的單詞${date} / ${time}:當前日期/時間${user}:當前系統用戶名${type_name} / ${method_name}:上下文類型/方法名(部分上下文可用)${primary_type_name}:包含模板的類名.epf 文件,納入項目規範,全團隊導入。log*、for*、try*,便於聯想搜索。EditorConfig + 共享代碼片段庫。