I'm a beginner to the Java programming language. I want to extract the AST from java source code and print the AST to a file or standard output.
I followed this tutorial to learn how to work with AST. http://www.programcreek.com/2011/01/a-complete-standalone-example-of-astparser/
So according to that the code I have so far is as follows.
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
public class Test {
public static void main(String args[]){
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource("public class A { int i = 9; \n int j; \n ArrayList<Integer> al = new ArrayList<Integer>();j=1000; }".toCharArray());
//parser.setSource("/*abc*/".toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
//ASTNode node = parser.createAST(null);
final CompilationUnit cu = (CompilationUnit) parser.createAST(null);
}
}
I tried the following code snippet to print it out to the standard output but it didn't give me the result I expected,
System.out.println(cu.getAST().toString());
If somebody could help me to print the AST out to a file it would be a great help.
Thanks in advance.
Here is an example of transforming the AST to JSON. You can modify the
JSONStyleASTPrinter.javafile to produce XML instead JSON etc.Based on example from How To Train the JDT Dragon combined.pdf: