Is it possible to access the Abstract Syntax Tree(AST) inside the javac.exe programmatically? Could you provide an example?
Yes, it is possible, but only since Java 6. Peter von der Ahé talks about the two JSRs in this interview. Of JSR 199:
The JSR 199 Compiler API consists of three things: The first one basically allows you to invoke a compiler via the API. Second, the API allows you to customize how the compiler finds and writes out files. I mean files in the abstract sense, since the files the compiler deals with aren't necessarily on the file system. JSR 199's file abstraction allows you to have files in a database, and to generate output directly to memory, for example. Finally, the JSR 199 API lets you collect diagnostics from the compiler in a structured way so that you can easily transform error messages, for instance, into lines in an IDE's editor.
JSR 269 is the annotation processing API.
This article gives an excellent overview of accessing the Compiler Tree API. The section "Accessing the Abstract Syntax Tree: The Compiler Tree API" seems particularly suitable for your question.
Depending on what you're doing, you may also want to look at the Jackpot Rule Language, which is a standalone refactoring engine that plugins into the Compiler Tree.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With