I'm trying to inline java method using eclipse jdt/ast.
For example, I'd like to make this code
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();
}
}
into this.
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");
}
}
I could get the body block of hello() method stored in Block bl
.
I also have the body block of main() method stored in Block block
, and I could delete hello(); ExpressionStatement
s in the block.
Then, I need to insert the Block bl
to where the hello();
is invoked.
I tried
block.statements().add(position, bl.getAST());
and
block.statements().add(position, bl);
where position
is the location of hello()
method in statements(), but both of them raises an error.
What might be wrong? As Block
is Statement
, I guess one can insert Block
in Block#statements()
.
ADDED
Based on sevenforce answer, I could get the block inserted, but I have the {
and }
included.
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");
}
}
}
Is there any way to remove them?
ADDED2
With this code:
ASTNode singleStmt = (ASTNode) bl.statements().get(0);
block.statements().add(position, ASTNode.copySubtree(bl.getAST(), singleStmt));
It shows only the first statement in hello()
method. For example, with
static void hello() {
System.out.println("hello");
System.out.println("hello2");
}
I have only System.out.println("hello");
inlined.