Java Eclipse抽象语法树编程访问
您能否提供一个示例,以编程方式访问给定代码段的Eclipse抽象语法树 例如,获得以下方面的AST:Java Eclipse抽象语法树编程访问,java,eclipse,abstract-syntax-tree,Java,Eclipse,Abstract Syntax Tree,您能否提供一个示例,以编程方式访问给定代码段的Eclipse抽象语法树 例如,获得以下方面的AST: Class1.java }这不是一个确切的答案,可能会给你一个起点: 如本文所述, 本文提供了一个完整的示例,更多详细信息请参见。在的幻灯片59中,您将看到如何对源代码应用更改 // get an ICompilationUnit by some means // you might drill down from an IJavaProject, for instance ICompila
Class1.java }这不是一个确切的答案,可能会给你一个起点: 如本文所述, 本文提供了一个完整的示例,更多详细信息请参见。在的幻灯片59中,您将看到如何对源代码应用更改
// 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与CompliationUnit之间的区别所迷惑,这似乎只是他们没有创造性命名的结果。CompliationUnit是ASTNode的一种类型。此上下文中的ICompilationUnit类似于文件句柄。有关区别的更多信息,请参见此处:
// 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);