【发布时间】:2012-10-08 20:41:21
【问题描述】:
我正在尝试使用 eclipse jdt/ast 内联 java 方法。
例如,我想做这段代码
class Hello {
static void hello() {
System.out.println("hello");
}
public static void main(String[] args) {
hello();
System.out.println("z");
hello();
System.out.println("h");
hello();
}
}
进入这个。
class Hello {
public static void main(String[] args) {
System.out.println("hello");
System.out.println("z");
System.out.println("hello");
System.out.println("h");
System.out.println("hello");
}
}
我可以得到 hello() 方法的主体块存储在Block bl 中。
我在Block block中也有main()方法的body块,我可以删除hello(); ExpressionStatements 在区块中。
然后,我需要将Block bl 插入到调用hello(); 的位置。
我试过了
block.statements().add(position, bl.getAST());
和
block.statements().add(position, bl);
其中position 是 statements() 中 hello() 方法的位置,但两者都会引发错误。
可能出了什么问题?由于Block 是Statement,我想可以在Block#statements() 中插入Block。
添加
根据 Sevenforce 的回答,我可以插入块,但我包含 { 和 }。
class Hello {
public static void main(String[] args) {
{
System.out.println("hello");
}
System.out.println("z");
{
System.out.println("hello");
}
System.out.println("h");
{
System.out.println("hello");
}
}
}
有什么办法可以去掉?
添加2
使用此代码:
ASTNode singleStmt = (ASTNode) bl.statements().get(0);
block.statements().add(position, ASTNode.copySubtree(bl.getAST(), singleStmt));
它只显示hello() 方法中的第一条语句。例如,与
static void hello() {
System.out.println("hello");
System.out.println("hello2");
}
我只有 System.out.println("hello"); 内联。
【问题讨论】:
标签: java eclipse abstract-syntax-tree eclipse-jdt