Eclipse 內置模板功能有限,自定義向導插件可強制團隊遵循統一代碼風格、目錄結構與最佳實踐。本文完整演示:創建插件項目 → 實現 INewWizard → 自定義向導頁面 → 驗證輸入 → 動態生成文件內容 → 擴展為項目級向導 → 部署與除錯。
File → New → Project → Plug-in Project,名稱 ExampleWizard;com.example.eclipse.wizards);Custom plug-in wizard → New File Wizard;NewXHTMLFileWizard,頁面類 NewXHTMLFileWizardPage。NewXHTMLFileWizard extends Wizard implements INewWizard {
addPages() // 添加頁面
performFinish() // 用戶點 Finish 觸發,用 IRunnableWithProgress 包裝耗時操作
doFinish() // 實際創建文件、寫入內容、打開編輯器
openContentStream() // 提供文件初始內容 InputStream
init() // IWorkbench 初始化上下文
}
private InputStream openContentStream() {
return this.getClass().getResourceAsStream("templates/index-xhtml-template.resource");
}
模板文件放在同包下 templates/ 目錄,內容為標準 XHTML 1.0 Strict 頁面,包含企業 CSS/JS 引用。
// 聲明控件
private Text titleText;
// createControl() 中添加
Label label = new Label(container, SWT.NULL);
label.setText("&Title:");
titleText = new Text(container, SWT.BORDER | SWT.SINGLE);
titleText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
titleText.addModifyListener(e -> dialogChanged());
// getter
public String getTitle() { return titleText.getText(); }
private void dialogChanged() {
// 容器存在性、可寫性、文件名合法性、擴展名必為 .html
if (titleText.getText().isEmpty()) { updateStatus("Title must be specified"); return; }
updateStatus(null); // 通過驗證,啟用 Finish
}
private InputStream openContentStream(String title) throws CoreException {
String line, nl = "\n"; StringBuffer sb = new StringBuffer();
try (BufferedReader r = new BufferedReader(new InputStreamReader(
this.getClass().getResourceAsStream("templates/index-xhtml-template.resource")))) {
while ((line = r.readLine()) != null) {
line = line.replaceAll("\\$\\{title\\}", title);
sb.append(line).append(nl);
}
} catch (IOException e) { throw new CoreException(...); }
return new ByteArrayInputStream(sb.toString().getBytes());
}
模板中 <title>${title}</title> 將被用戶輸入替換。
NewSiteProjectWizard 實現 INewWizard + IExecutableExtension;WizardNewProjectCreationPage 獲取項目名/位置;performFinish() 調用 WorkspaceModifyOperation 創建項目、文件夾、文件;NewXHTMLFileWizard.openContentStream() 生成 index.html;styles/site.css、images/ 目錄結構。<extension point="org.eclipse.ui.newWizards">
<category name="Example.com Enterprise Templates" id="ExampleWizard"/>
<wizard name="Example.com Static Web Page" class="...NewXHTMLFileWizard" category="ExampleWizard"/>
<wizard name="Example.com Static Web Site" class="...NewSiteProjectWizard" category="ExampleWizard" project="true"/>
</extension>
eclipse/plugins/(勿解壓);-clean 解決標識符/版本錯誤;Run → Debug Last Launched 進入調試視角,在 performFinish() 首行打斷點;企業級向導能將「約定優於配置」落地為工具強制約束,顯著提升團隊協作一致性與新人上手效率。