Manipulating code with a preview in a Java editor

The JDT Core plugin provides several mechanisms to programmatically create, delete and modify Java elements. See manipulating Java code for an introducation to the API provided by JDT Core.

In a UI world it is often useful to have the user confirm a preview before changes are saved. This can be achieved by opening a Java editor on the compilation unit to be modified. The user can then either save the Java editor's content to disk or revert it back to its original content. Below is a code snippet that opens a compilation unit in an editor and then uses the working copy created by the editor to perform the changes:

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.