java modify的使用方法图解,经过JDT修改(Modify)Java代码的流程步骤

通过JDT修改(Modify)Java代码的流程步骤

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(更加强大)也是可以的,将在后续博文中进行总结。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值