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?
You can use the below code to achieve this (this will add the sysout just before the first
IfStatement
) :Also you can limit the scope of rewrite to the
IfStatement
:Note: code not tested. Do let me know if you find any issues.