Eclipse Abstract Syntax for Programmatic Access Tree

Could you provide an example of accessing the abstract Eclipse syntax tree programmatically for a given piece of code?

for example, obtaining AST for:


Class1.java

package parseable;

public class Class1 {

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

}

+3
source share
2 answers

This is not an exact answer that may give you a place to start:

As said in this question ,

A full example is available in this eclipse eclipse article , as well as more details on eclipse help . And in slide 59 of this presentation, you see how to apply the change to the source code.

+3
source
// 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 vs CompilationUnit, , -, . CompilationUnit - ASTNode. ICompilationUnit . . : http://wiki.eclipse.org/FAQ_How_do_I_manipulate_Java_code%3F

+1

Source: https://habr.com/ru/post/1698197/


All Articles