JDT:替换MethodInvocation时缺少分号

4
我正在尝试使用Eclipse JDT的AST模型将一个方法调用替换为另一个。以一个简单的例子为例 - 我想用System.out.println()替换所有对Log.(i/e/d/w)的调用。我使用一个ASTVisitor来定位有趣的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")

注意: 语句末尾缺少分号

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

1个回答

4

找到了答案。诀窍是将newMethodInvocation对象包装在ExpressionStatement类型的对象中,就像这样:

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

基本上,用上述两行代码替换我的示例代码中的最后一行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接