Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javac.exe AST programmatic access example

Is it possible to access the Abstract Syntax Tree(AST) inside the javac.exe programmatically? Could you provide an example?

like image 449
hawkeye Avatar asked Oct 13 '08 09:10

hawkeye


1 Answers

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.

like image 133
jamesh Avatar answered Sep 27 '22 17:09

jamesh