3

您能否提供一个以编程方式访问给定代码的 Eclipse 抽象语法树的示例?

例如获取 AST 用于:


Class1.java

package parseable;

public class Class1 {

/**
 * @param args
 */
public static void main(String[] args) {
    System.out.println("Hello world!");
}

}

4

2 回答 2

3

这不是一个确切的答案,可能会给您一个开始的地方:

正如在这个问题中所说,

Eclipse 角文章中提供了完整示例,更多详细信息请参见Eclipse 帮助。在本演示文稿的幻灯片 59 中,您将了解如何将更改应用到您的源代码。

于 2008-10-13T09:15:02.073 回答
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

于 2011-07-03T20:08:05.250 回答