在编辑器中使用工作副本

“JDT 核心”插件提供了 API 来允许使用程序来创建、删除和修改 Java 元素。有关由“JDT 核心”提供的 API 的简介,参见处理 Java 代码。  

Java 模型中的一个重要概念是使用编译单元的内存内副本,称为“工作副本”(IWorkingCopy)。对工作副本的使用允许先使用程序来更改编译单元,然后再将更改提交给底层资源。 

在 Java 用户界面中,一个并行概念是允许用户在将工作副本提交给文件系统之前对资源进行广泛的编辑。通过使用副本,用户界面实现可以允许用户将 Java 编辑器的内容保存至磁盘或者将它回复到其原始内容。   

IWorkingCopyManager 管理编辑器内使用的 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, 2003. All Rights Reserved.