Represent a Java file as an AST(Abstract Syntax Tree)

You may wonder what a Java class looks like as an Abstract Syntax Tree(AST).

We can view AST of any Java class by using Eclipse ASTView. The AST can be easily showed in a separate view under eclipse IDE.

For the following simple java class, the ASTView shows the complete AST.

public class Test {
	public int add(int a, int b){
		int c = a+b;
		return c;
	}
}

When you write a visitor to visit each node of a AST, the nodes in bold font are accessible to visitor(s). For example, MethodDeclaration, Modifier, SimpleName, SingleVariableDeclaration, etc. Others can be accessed by using some methods of those bold classes.

When look at the view, we can see that the AST created for this class has the following hierarchy. As it is shown in the diagram, even a very simple class need a big AST to represent.

AST of a Java Class

Now the question is in what order a visitor would visit each node of the AST. The answer is depth-first, i.e., the class then each method.

Here is the link to get ASTView for your eclipse. Download Link (Select the right version for you eclipse.)

5 thoughts on “Represent a Java file as an AST(Abstract Syntax Tree)”

  1. How can i print this AST tree as string for any java program ?

    Problem: i want to print the Abstract Syntax Tree of any java program, which is shown in ASTView plugin by using any API.

  2. Use ASTVistor to visit the nodes you are interested in, such as a TypeDeclaration, MethodDeclaration, etc.

  3. I am working on a project with ast analyzing. I am so curious how you extracted the information from the bunch of data which is shown in astview in eclipse (like your diagram). I need a simplistic tree of the source code. Can you help me to do this task

Leave a Comment