[英]Eclipse Abstract Syntax Tree Programmatic Access
您能否提供一個以編程方式為給定代碼段訪問Eclipse Abstract Syntax Tree的示例?
例如,獲取AST:
package parseable;
public class Class1 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
這不是一個確切的答案,可能會給你一個開始的地方:
正如這個問題所說,
這個eclipse角文章中提供了一個完整的例子,還有eclipse幫助中的更多細節。 在本演示文稿的幻燈片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與CompilationUnit區分混淆,這似乎只是他們自己命名的命名的結果。 CompilationUnit是一種ASTNode。 此上下文中的ICompilationUnit類似於文件句柄。 有關區別的更多信息,請參見此處: http : //wiki.eclipse.org/FAQ_How_do_I_manipulate_Java_code%3F
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.