Tom Ball, an engineer with Sun's developer tools team, posted a recent blog entry about taking advantage of new Java compiler features to get better insight into source code. The post is a good review of new and upcoming features for programmatic access to Java source code.
Tom Ball starts out his latest blog post, Hacking javac, saying that compilers might on the surface seem boring tools useful only to turn source code into code for some execution set, such as the JVM. However, as he notes,
If the compiler is designed to function as a tool library, as javac is, much more interesting (and benign) hacks are possible.
He then proceeds to present three javac "hacks," using APIs that will become generally available in JDK 6:
Programmatically listen to errors and warnings from the compiler. This can be useful in tools and editors to indicate coding and syntax errors:
[This] leverages JSR 199's [Java Compiler API] DiagnosticListener interface... JSR 199 improves on the old trick of parsing error strings with Diagnostic instances, which provide accurate source position information, and locale-independent error IDs with locale-specific error text... [For instance, in NetBeans 6], compilation is run regularly in the background but only the diagnostic events are used.
Instead of interpreting, say, a scripting language, write a compiler that produces Java bytecode on the fly from the scripting language source code. Once the Java classes are compiled, you don't have to write those classes to disk, but use the Compiler API's class loader can load those newly compiled classes. The benefit of this maybe increased speed in running the scripting language code, because, as Ball points out, javac does compilation very fast:
[In NetBeans], we used to conditionally compile scripts only if they had changed, but found that javac is so fast that caching didn't make a difference.
Use the JSR 269 Pluggable Annotation Processing API to inspect source code on the fly for coding rules This would give you features similar to FindBugs:
A general way to think of JSR 269 is that it gives you access to all of the types and elements (symbols) in any set of source files, not just its annotations. Its javax.lang.model.util package has easily extensible visitor and scanner base classes which can be used by tools to inspect projects at the semantic level... One advantage of using JSR-269 types and elements rather than your own parser for these sorts of tests is that while you can infer many properties from a parse tree, the javac semantic model knows the correct properties.
What do you think of these "compiler hacks?" In what ways can you imagine extending your toolset with these new features in order to produce higher-quality code?