您是否可以提供一个以编程方式访问Eclipse Abstract Syntax Tree的示例代码?
例如获取AST:
package parseable;
public class Class1 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
答案 0 :(得分:3)
这不是一个完全的答案,可能会给你一个开始的地方:
正如question中所说,
此eclipse corner article中提供了完整示例,eclipse help中还提供了更多详细信息。在this presentation的幻灯片59中,您可以看到如何对源代码应用更改。
答案 1 :(得分:1)
// get an ICompilationUnit by some means
// you might drill down from an IJavaProject, for instance
ICompilationUnit iunit = ...
// create a new parser for the latest Java Language Spec
ASTParser parser = ASTParser.newParser(AST.JLS3);
// tell the parser you are going to pass it some code where the type level is a source file
// you might also just want to parse a block, or a method ("class body declaration"), etc
parser.setKind(ASTParser.K_COMPILATION_UNIT);
// set the source to be parsed to the ICompilationUnit
// we could also use a character array
parser.setSource(iunit);
// parse it.
// the output will be a CompilationUnit (also an ASTNode)
// the null is because we're not using a progress monitor
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
不要被ICompilationUnit与CompilationUnit区分混淆,这似乎只是他们自己命名的命名的结果。 CompilationUnit是一种ASTNode。此上下文中的ICompilationUnit类似于文件句柄。有关区别的更多信息,请参阅此处:http://wiki.eclipse.org/FAQ_How_do_I_manipulate_Java_code%3F