[JSR308] Modifying the annotations in the source
Mahmood Ali
mahmood at MIT.EDU
Thu Jan 22 20:52:07 EST 2009
Greetings Niko,
> Is it possible for a Checker to affect the annotations which will be
> written into the .class file?
The compiler public API only provides a read-only view of the trees
and the java symbols.
It's possible to manipulate the compiler structures by casting them to
the javac internal structure and manipulating the annotations fields
(e.g. Tree to JCTree and Element to Symbol). The approach is a bit of
gotcha points though:
1. A tree clean up routine is invoked after annotation processing
phase. As far as I can tell/remember it only removes the Symbol
information from the tree, so it would be recalculated later. If you
simply manipulate the Element information, those changes might be lost
before reaching code generation stage. Also, you would need to use
the AnnotationMirror compiler implementation (Attribute.Compound)
rather than you own.
2. You might be better off, manipulating the tree itself, by using
TreeMaker. This page (http://www.ahristov.com/tutorial/java-compiler/new-operator.html
) explains some of the TreeMaker API points. However, the code
samples aren't applicable to your case directly.
3. The List structures in the compiler (to hold annotations of a
symbol) is an immutable List. .add() methods throw an Exception, so
you should use append() which returns a new List. Hence, the pattern
in the compiler of:
mods.annotations = mods.annotations.appendList(atype.annotations);
4. You should never reuse generated trees of annotation mirrors, i.e.
create one Attribute.Compound and add to multiple methods. You would
need to create a new one for each use.
Another approach is to have the checker output an annotation file then
have the insert-annotation utility tool (http://groups.csail.mit.edu/pag/jsr308/annotation-file-utilities/
) insert the annotations to the class files afterwards.
Hope this helps.
Regards,
Mahmood
More information about the JSR308
mailing list