Wednesday, July 11, 2012

Java's Annotation Processing API

Okay, I haven't posted in a long time, but I just want a quick note to say, Java's Annotation Processing API is absolutely amazing.

It takes a little while to get used to using mirrors rather than reflection, but once things fall into place, you can do amazing amounts of metaprogramming with it.

I had a project which was processing properties found in data-model classes (classes which map directly to tables in a database), and we were processing these properties via certain annotations.

Unfortunately, I didn't take into account the need to annotate methods in the model classes as well, and that requirement came in very shortly after I released the processor.

Within 10 minutes I was able to swap out the processing upon a VariableElement to simply an Element class, and not have to introduce any new code to adjust for processing a method versus a property.

Okay, I had one minor adjustment.  VariableElement has an "asType()" method which returns the TypeMirror for the static type of a property.  ExecutableElement (a method) has a "getReturnType()" method which returns the TypeMirror for the method.  I had to do a little bit of processing on the types to make sure I get their return types properly extracted.

Other than that, however, it was nice and clean.