【发布时间】:2014-03-11 06:20:00
【问题描述】:
我正在尝试使用 Eclipse 插件、JDT 和 AST(抽象语法树)来修改源代码。我可以读取所有 Java 文件并对所有这些文件进行操作,但是当我使用
将这些更改(编辑)保存到文件中时 TextEdit edits = rewriter.rewriteAST();
// apply the text edits to the compilation unit
edits.apply(document);
iCompilationUnit.getBuffer().setContents(document.get());
它只对在 eclipse 中以未保存模式打开的文件进行更改。其余文件不受影响。
在下面找到我的代码 sn-p:
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());
【问题讨论】:
标签: eclipse-plugin abstract-syntax-tree eclipse-jdt