Eclipse Java AST解析器:在if / for / while之前插入语句 [英] Eclipse Java AST parser: insert statement before if/for/while

查看:133
本文介绍了Eclipse Java AST解析器:在if / for / while之前插入语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用org.eclipse.jdt解析器。

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

我想重写以下代码:

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

为此:

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

假设ifnode是IF_STATEMENT节点,我可以做类似的事情:

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

但这将在方法的开头插入syso语句,而我希望它在如果。

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

有办法实现吗?

推荐答案

您可以使用下面的代码来实现这一点(这将在第一个 IfStatement 之前添加sysout):

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

也可以将重写范围限制为 IfStatement

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.

这篇关于Eclipse Java AST解析器:在if / for / while之前插入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆