代码之家  ›  专栏  ›  技术社区  ›  hawkeye

Eclipse抽象语法树编程访问

  •  3
  • hawkeye  · 技术社区  · 16 年前

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

    例如,获取AST用于:


    类1.java

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

    }

    2 回复  |  直到 13 年前
        1
  •  3
  •   Community datashaman    7 年前

    它不是一个 准确的 回答,这可能会给你一个开始的地方:

    正如在这里所说的 question ,

    这里有一个完整的例子 eclipse corner article ,更多详细信息请参见 eclipse help . 在第59张幻灯片中, this presentation ,您将看到如何对源代码应用更改。

        2
  •  1
  •   johncip    13 年前
    // 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