Eclipse AST是Eclipse JDT的一个重要组成部分,定义在org.eclipse.jdt.core.dom中,用来表示java语言中的所有语法结构。下面是api中一些核心类的概念:
1.ASTNode类及其派生类
用于描述各种AST节点的类,每个AST节点表示一个Java源程序中的一个语法结构,例如,类型、表达式、语句或声明等。
2.AST类
创建AST节点的工厂类,类中包含许多创建各类AST节点的工厂方法,程序员可以利用这些方法来创建AST.
3.ASTVisitor类
AST的访问者抽象类,类中声明了一组访问各类AST节点的visit(),endVisit(),preVisit()方法。
4.ASTRewrite类
AST中跟持久相关的类,它的功能跟CompilationUnit.rewrite类似,只是它可以很好的处理多个源交替进行覆盖java文件的问题。下面是官方的例子。
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();
}