Eclipse AST 不更改未在 Eclipse 中打开的文件 [英] Eclipse AST not changing files which are not opened in eclipse
本文介绍了Eclipse AST 不更改未在 Eclipse 中打开的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用 eclipse 插件、JDT 和 AST(抽象语法树)修改源代码.我可以读取所有 Java 文件并对所有这些文件进行操作,但是当我使用
I am trying to modify source code using eclipse plugin, JDT and AST (Abstract Syntax Tree). I can read all Java files and make operation on all those file, But when i am saving those changes (Edits) in to files using
TextEdit edits = rewriter.rewriteAST();
// apply the text edits to the compilation unit
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
它只对在 eclipse 中以未保存模式打开的文件进行更改.其余文件不受影响.
It only make changes in file those are open in eclipse in unsaved mode. Rest of files are not affected.
在下面找到我的代码片段:
Find my code snippet below:
CompilationUnit cu = parse(iCompilationUnit);
MethodVisitor visitor = new MethodVisitor();
cu.accept(visitor);
String source = iCompilationUnit.getSource();
Document document= new Document(source);
ASTRewrite rewriter = ASTRewrite.create(cu.getAST());
cu.recordModifications();
for (MethodDeclaration methodDeclaration : visitor.getMethods()) {
System.out.print("Method name: " + methodDeclaration.getName()
+ " Return type: " + methodDeclaration.getReturnType2());
MethodDeclaration methodDecl = methodDeclaration;
Block block = methodDecl.getBody();
ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);
Statement placeHolder = (Statement) rewriter.createStringPlaceholder("System.out.println("Test Print");", ASTNode.EMPTY_STATEMENT);
listRewrite.insertFirst(placeHolder, null);
}
TextEdit edits = rewriter.rewriteAST();
// apply the text edits to the compilation unit
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
推荐答案
尝试:
- 将 TextEdit 直接应用于 ICompilationUnit,而不是使用 Document.
- 使用 ICompilationUnit.commitWorkingCopy 保存更改
我使用类似的代码:
iCompilationUnit.becomeWorkingCopy(new NullProgressMonitor());
CompilationUnit cu = parse(iCompilationUnit);
ASTRewrite rewriter = ASTRewrite.create(cu.getAST());
... process AST ...
iCompilationUnit.applyTextEdit(rewrite.rewriteAST(), new NullProgressMonitor());
iCompilationUnit.commitWorkingCopy(false, new NullProgressMonitor());
这篇关于Eclipse AST 不更改未在 Eclipse 中打开的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文