JDT Core 外掛程式提供許多機制,讓您以程式設計方式來建立、刪除與修改 Java 元素。 有關 JDT Core 所提供之 API 的介紹,請參閱運用 Java 程式碼。
在 UI 環境中,讓使用者在儲存變更前先確認預覽相當有幫助。 如果要如此做,請針對所要修改的編譯單元開啟一個 Java 編輯器。 接著,使用者可將 Java 編輯器中的內容儲存到磁片中, 或回復成原來的內容。以下的程式碼片段是在編輯器中開啟一個編譯單元, 並使用編輯器所建的工作副本來進行變更:
void modifyCompilationUnit(ICompilationUnit cunit) throws PartInitException, CoreException {
IEditorPart editor= JavaUI.openInEditor(cunit);
IEditorInput input= editor.getEditorInput();
IWorkingCopyManager manager= JavaUI.getWorkingCopyManager();
manager.connect(input);
try {
ICompilationUnit workingCopy= manager.getWorkingCopy(input);
// 使用一般 JDT Core API 來修改 workingCopy。 } finally {
manager.disconnect(input);
}
// 讓編輯器維持在已用過狀態,或使用 editor.doSave(IProgressMonitor monitor) // 來儲存程式設計上的變更。
}