Search code examples
javaeclipse-jdt

How to use ASTRewrite to insert a code snippet insert a method's body?


I´m using JDT in Eclipse Neon to write a Java code generator plug-in. In a certain moment I already have the AST of a correctly generated class and a method with an empty body, like the one below:

// Simplified for this question
public class X {
  public void x(void) {
  }
}

Now I have a code snippet in a StringBuilder instance ready to be used as the code for that empty method body. The code is correctly written, so, after inserted, it will compile with no errors.

After going through a number of posts, foruns and the JDT documentation, I could not find a way to insert that code snippet in the AST.

PS.: One of my attemps was to use the ASTParser class to generate a new AST from my snippet, what in fact works. However, since the snippet's AST is not the same as the target class AST, it cannot be used as method body.


Solution

  • If you already have AST for your method body, you can insert it into the method after copying it to the correct AST instance. See method org.eclipse.jdt.core.dom.ASTNode.copySubtree(AST, ASTNode)

    Alternatively, if you control the moment, when the ASTRewrite produces TextEdits you could perhaps just directly add an InsertEdit of your own, before all edits together are applied. In this scenario, finding the correct offset for insertion could be the tricky part.