JDT: Missing semicolon when replacing Invocation method with another

I am trying to use the Eclipse JDT AST model to replace one MethodInvocation with another. To take a trivial example - I'm trying to replace all calls with Log.(i/e/d/w) with calls to System.out.println() . I use ASTVisitor to find an interesting ASTNode and replace it with a new MethodInvocation node. Here is the code diagram:

 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); } } } 

This rewrite is then saved in the original document. All this works great, but for one small problem - the original statement:

 Log.i("Hello There"); 

changes to:

 System.out.println("Hello There") 

NOTE : there is no semicolon at the end of the statement

QUESTION : how to insert a semicolon at the end of a new statement?

+4
source share
1 answer

Found the answer. The trick is to wrap the newMethodInvocation object in an ExpressionStatement object like this:

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

Essentially replace the last line in my sample code with the two above lines.

+4
source

All Articles