借助 Java 编辑器中的预览来处理代码

“JDT 核心”插件提供了几种机制来使用程序创建、删除和修改 Java 元素。有关由“JDT 核心”提供的 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);
// do the modifications on workingCopy using the normal JDT Core API. } finally {
manager.disconnect(input);
}
// either keep the editor dirty or use editor.doSave(IProgressMonitor monitor) // to save the changes programmatically.
}

Copyright IBM Corporation and others 2000, 2002. All Rights Reserved.