Previewing Java code manipulations

The JDT Core plug-in provides API that allows you to programmatically create, delete and modify Java elements. See manipulating Java code for an introduction to the API provided by JDT Core.  

An important concept in the Java model is the use of an in-memory copy of a compilation unit, called a "working copy" (IWorkingCopy).  Using a working copy allows you to perform significant changes on a compilation unit before committing the changes to the underlying resource.

In the Java user interface, a parallel concept is to allow the user to extensively edit a resource before committing the working copy to the file system.  This is achieved by opening a Java editor on a working copy rather than its associated resource.  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 a working copy as the input so that the changes are made to the copy rather than the resource:

    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.