Eclipse Java AST parser: insert statement before i

2019-05-30 09:25发布

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?

1条回答
我想做一个坏孩纸
2楼-- · 2019-05-30 10:10

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.

查看更多
登录 后发表回答