I use the grammar Java.g from the ANTLR wiki produces a lexer and parser for Java source files.Then use the following code to generate an AST.
InputStream inputStream = new FileInputStream(fileName);
ANTLRInputStream input = new ANTLRInputStream(inputStream);
JavaLexer lexer = new JavaLexer(input);
CommonTokenStream tokens = new CommonTokenStream();
tokens.setTokenSource(lexer);
JavaParser javaParser = new JavaParser(tokens);
RuleReturnScope result = javaParser.compilationUnit();
CommonTree commonTree = (CommonTree) result.getTree();
commonTree = (CommonTree) commonTree.getChild(1);
commonTree.toStringTree();
//printTree(commonTree, 0);
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(commonTree);
System.out.println(st);
We can visualize this AST by copy-pasting the DOT-source in here: http://graphviz-dev.appspot.com . The question is how can I convert the AST to java? I want to modify the AST,then convert the modified AST to java.