hawkeye
hawkeye

Reputation: 35702

Eclipse Abstract Syntax Tree Programmatic Access

Could you provide an example of accessing the Eclipse Abstract Syntax Tree programmatically for a given piece of code?

eg getting the AST for:


Class1.java

package parseable;

public class Class1 {

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

}

Upvotes: 3

Views: 1216

Answers (2)

johncip
johncip

Reputation: 2259

// 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);

Don't be confused by the ICompilationUnit vs CompilationUnit distinction, which seems to be just the result of uncreative naming on their part. CompilationUnit is a type of ASTNode. ICompilationUnit in this context resembles a file handle. For more info on the distinction, see here: http://wiki.eclipse.org/FAQ_How_do_I_manipulate_Java_code%3F

Upvotes: 1

VonC
VonC

Reputation: 1323953

It is not an exact answer, that may give you a place where to start:

As said in this question,

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

Upvotes: 3

Related Questions