4

我正在尝试使用 Eclipse JDT 的 AST 模型来替换MethodInvocation另一个。举一个简单的例子 - 我试图Log.(i/e/d/w)用调用替换所有调用 to System.out.println()。我正在使用 anASTVisitor来定位有趣 ASTNode的节点并将其替换为新MethodInvocation节点。这是代码的概要:

class StatementVisitor extends ASTVisitor {

    @Override
    public boolean visit(ExpressionStatement node) {

        // If node is a MethodInvocation statement and method
        // name is i/e/d/w while class name is Log

        // Code omitted for brevity

        AST ast = node.getAST();
        MethodInvocation newMethodInvocation = ast.newMethodInvocation();
        if (newMethodInvocation != null) {
            newMethodInvocation.setExpression(
                ast.newQualifiedName(
                    ast.newSimpleName("System"), 
                    ast.newSimpleName("out")));
            newMethodInvocation.setName(ast.newSimpleName("println"));

            // Copy the params over to the new MethodInvocation object
            mASTRewrite.replace(node, newMethodInvocation, null);
        }
    }
}

然后将此重写保存回原始文档。整个事情运行良好,但对于一个小问题 - 原始声明:

Log.i("Hello There");

更改为:

System.out.println("Hello There")

注意:语句末尾的分号丢失

问题:如何在新语句的末尾插入分号?

4

1 回答 1

4

找到了答案。诀窍是将对象包装newMethodInvocation在如下类型的对象中ExpressionStatement

ExpressionStatement statement = ast.newExpressionStatement(newMethodInvocation);
mASTRewrite.replace(node, statement, null);

本质上,将我的代码示例中的最后一行替换为上述两行。

于 2013-03-01T05:29:03.473 回答