Class ASTRewrite

java.lang.Object
org.aspectj.org.eclipse.jdt.core.dom.rewrite.ASTRewrite

public class ASTRewrite extends Object
Infrastructure for modifying code by describing changes to AST nodes. The AST rewriter collects descriptions of modifications to nodes and translates these descriptions into text edits that can then be applied to the original source. The key thing is that this is all done without actually modifying the original AST, which has the virtue of allowing one to entertain several alternate sets of changes on the same AST (e.g., for calculating multiple quick fix proposals). The rewrite infrastructure tries to generate minimal text changes, preserve existing comments and indentation, and follow code formatter settings.

The following code snippet illustrated usage of this class:

 Document document = new Document("import java.util.List;\nclass X {}\n");
 ASTParser parser = ASTParser.newParser(AST.JLS3);
 parser.setSource(document.get().toCharArray());
 CompilationUnit cu = (CompilationUnit) parser.createAST(null);
 AST ast = cu.getAST();
 ImportDeclaration id = ast.newImportDeclaration();
 id.setName(ast.newName(new String[] {"java", "util", "Set"}));
 ASTRewrite rewriter = ASTRewrite.create(ast);
 TypeDeclaration td = (TypeDeclaration) cu.types().get(0);
 ITrackedNodePosition tdLocation = rewriter.track(td);
 ListRewrite lrw = rewriter.getListRewrite(cu, CompilationUnit.IMPORTS_PROPERTY);
 lrw.insertLast(id, null);
 TextEdit edits = rewriter.rewriteAST(document, null);
 UndoEdit undo = null;
 try {
     undo = edits.apply(document);
 } catch(MalformedTreeException e) {
     e.printStackTrace();
 } catch(BadLocationException e) {
     e.printStackTrace();
 }
 assert "import java.util.List;\nimport java.util.Set;\nclass X {}\n".equals(document.get());
 // tdLocation.getStartPosition() and tdLocation.getLength()
 // are new source range for "class X {}" in document.get()
 

If you are sure you never have to explore multiple alternate changes and you never need to create copies or string placeholders, then you can also try CompilationUnit.recordModifications() instead.

ASTRewrite cannot rewrite (non-Javadoc) comments from CompilationUnit.getCommentList(), since those comment nodes are not part of the normal node hierarchy.

This class is not intended to be subclassed.

Since:
3.0