How to generate AST from Java source-code? [closed]
Solution 1:
Regarding your second question, there are dozens of Java parsers available in addition to Sun's. Here is a small sample:
- Eclipse's org.eclipse.jdt.core.dom package.
- Spoon outputs a very nice annotated parse tree with type information and variable binding (and uses Eclipse's parser internally)
- ANTLR is a parser-generator, but there are grammars for Java available
- javaparser (which I have not used)
My best advice is to try each of them to see which works best for your needs.
Solution 2:
You can possibly take the tools.jar and use it. javac is open source so you can just grab that code (assuming you can deal with the license). Antlr has grammars for Java as well.
Solution 3:
I've used Eclipse's AST parser. I found it to be pretty good (well it was part of an Eclipse plug-in so it did make sense to use it). See Exploring Eclipse's ASTParser.
Solution 4:
A working, simple to use Java Parser is... JavaParser. The project has been active for some years already. While it was initially hosted on Google code it is now available on GitHub: https://github.com/javaparser/javaparser
It is quite simple to use and the number of dependencies is small. It is also available on Maven.
It has been used for a few years, so it works quite well and permits to parse also comments, to change the AST and regenerate the code.
Solution 5:
I've just come across Jexast, an extraction of the JDT's ASTParser to work independent of Eclipse (it depends on org.eclipse.jdt.internal.compiler.**
).
I haven't tried it yet, but it does seem interesting.