Search code examples
javaeclipseparsingabstract-syntax-treeeclipse-jdt

Eclipse Java AST parser: insert statement before if/for/while


I'm using the org.eclipse.jdt parser.

I want to rewrite this code:

public void foo(){
...
...
if(a>b)
...
...
}

into this:

public void foo(){
...
...
System.out.println("hello");
if(a>b)
...
...
}

Supposing that ifnode is an IF_STATEMENT node, I can do something similar to this:

Block block = ast.newBlock();
TextElement siso = ast.newTextElement();
siso.setText("System.out.println(\"hello\");");

ListRewrite listRewrite = rewriter.getListRewrite(block, Block.STATEMENTS_PROPERTY);    
listRewrite.insertFirst(ifnode, null);
listRewrite.insertFirst(siso, null);

rewriter.replace(ifnode, block, null);

but this will insert the syso statement at the beginning of the method, while I want it right before the if.

Is there a way to achieve it?


Solution

  • You can use the below code to achieve this (this will add the sysout just before the first IfStatement) :

    Block block = ast.newBlock();
    TextElement siso = ast.newTextElement();
    siso.setText("System.out.println(\"hello\");");
    
    ListRewrite listRewrite = rewriter.getListRewrite(block,  CompilationUnit.IF_STATEMENT);    
    listRewrite.insertFirst(siso, null);
    
    TextEdit edits = rewriter.rewriteAST(document, null);
    

    Also you can limit the scope of rewrite to the IfStatement:

    ASTRewrite rewriter = ASTRewrite.create(ifNode.getAST());
    

    Note: code not tested. Do let me know if you find any issues.