2013-03-01 15 views
4

我想用Eclipse JDT的AST模型替换另一个MethodInvocation。举一个微不足道的例子 - 我试图用System.out.println()来呼叫Log.(i/e/d/w)。我正在使用ASTVisitor来定位有趣的ASTNode,并用新的MethodInvocation节点替换它。这里是代码的概要:JDT:用另一个替换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

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

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

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