ASTRewrite
From Arnout Engelen
In fact, current ASTRewrite API allow you to add comment in the code... Here's an example of what can be done with it:
[edit] Example code
Let's say that cu was the ICompilationUnit corresponding to following java file:
package test1;
public class E {
public void foo() {
while (i == j) {
System.beep();
}
}
}
Let's say that you want to add a block comment before beep method invocation. Then following code is an example of doing it using ASTRewrite API:
// Create ASTRewrite object from compilation unit
CompilationUnit astRoot= createAST(cu);
ASTRewrite rewrite= ASTRewrite.create(astRoot.getAST());
// Get while statement block
TypeDeclaration typeDecl = (TypeDeclaration) astRoot.types().get(0);
MethodDeclaration methodDecl= typeDecl.getMethods()[0];
Block block= methodDecl.getBody();
List statements= block.statements();
WhileStatement whileStatement= (WhileStatement) statements.get(0);
Statement whileBlock= whileStatement.getBody();
// insert block comment as first statement
StringBuffer comment = new StringBuffer();
comment.append("/*\n");
comment.append(" * Here's the block comment I want to insert :-)\n");
comment.append(" */");
ASTNode placeHolder= rewrite.createStringPlaceholder(comment.toString(), ASTNode.RETURN_STATEMENT);
ListRewrite list = rewrite.getListRewrite(whileBlock, Block.STATEMENTS_PROPERTY);
list.insertFirst(placeHolder, null);
// Get new code
String preview= evaluateRewrite(cu, rewrite);
Then preview looks now as follow: package test1;
public class E {
public void foo() {
while (i == j) {
/*
* Here's the block comment I want to insert :-)
*/
System.beep();
}
}
}
