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

半世苍凉 提交于 2020-01-14 03:05:52

问题


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:


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.



来源:https://stackoverflow.com/questions/29111704/eclipse-java-ast-parser-insert-statement-before-if-for-while

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!