1.ICompilationUnit originalUnit = ...;// Get original compilation unit
获取ICompilationUnit实例的方式很简单,此处不再详述。
2.originalUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1));//得到编译单元的工作副本
说明:将编译单元切换到工作副本模式,就是在内存中创建一块存放Java代码副本的地方,即工作副
本缓存。工作副本模式下,工作副本可以得到工作副本缓存,一个IBuffer的实例。该实例类似于
StringBuffer的API,对其修改就可以达到修改与之关联的 Java元素的效果。在提交代码之前,对缓存
修改一直保存在工作副本中,直至被显式提交。
3.IBuffer buffer = originalUnit.getBuffer(); // 得到工作副本缓存
eg:
//Modify buffer and reconcile
IBuffer buffer = ((IOpenable)workingCopy).getBuffer();
buffer.append("class X {}");
4.JavaModelUtil.reconcile(originalUnit); //同步
或workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
5.originalUnit.commitWorkingCopy(true, monitor);//保存。修改完毕,需要将代码的变化提交才能保存到磁盘上
6.if(originalUnit != null)
copyCU.discardWorkingCopy();//为了防止资源浪费,提交之后,丢弃副本
附录中是Eclipse官方帮助所提供的说明及示例流程代码。
注:通过applyTextEdit也是可以的。
For example the following code snippet creates a working copy on a compilation unit using a custom working copy owner. The snippet modifies the buffer, reconciles the changes, commits the changes to disk and finally discards the working copy.
//Get original compilation unit
ICompilationUnit originalUnit = ...;
//Get working copy owner
WorkingCopyOwner owner = ...;
//Create working copy
ICompilationUnit workingCopy = originalUnit.getWorkingCopy(owner, null);
// Modify buffer and reconcile
IBuffer buffer = ((IOpenable)workingCopy).getBuffer();
buffer.append("class X {}");
workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
// Commit changes
workingCopy.commitWorkingCopy(false, null);
// Destroy working copy
workingCopy.discardWorkingCopy();
The compilation unit's buffer can also be modified using the ICompilationUnit.applyTextEdit method.
//Get original compilation unit
ICompilationUnit originalUnit = ...;
//Get working copy owner
WorkingCopyOwner owner = ...;
//Create working copy
ICompilationUnit workingCopy = originalUnit.getWorkingCopy(owner, null);
//Get text edits
TextEdit edit = ...;
//Modify buffer and reconcile
workingCopy.applyTextEdit(edit, null);
workingCopy.reconcile(ICompilationUnit.NO_AST, false, null, null);
//Commit changes
workingCopy.commitWorkingCopy(false, null);
//Destroy working copy
workingCopy.discardWorkingCopy();
总之,针对单个编译单元的修改的步骤是将工作单元转化为工作副本,得到工作副本缓存;修改缓存并定时与原文件同步;提交变化、丢弃副本来保存文件。另外,通过DOM/AST所提供的API(更加强大)也是可以的,将在后续博文中进行总结。