[JSR308] Runtime access to JSR-308 annotations
subanark at gmail.com
Tue Sep 16 13:11:26 EDT 2008
You can use TreeUtils.elementFromUse to get an element corresponding to a
field, local variable or method invocation from an Tree (some objects such
as string literals don't have definitions, and therefore cannot have
annotations). You can do this either while traversing the AST in the Visitor
class (if you want to give errors for incorrect use), or in
annotationImplicit(Tree,AnnotatedTypeMirror) method (if you want to apply
different annotation than those declared on the defination). Once you have
the element you can get its type with Element.asType(). Next you need to
determine if this type has a defination (primatives and arrays don't have
definations); use getKind() and check if it is TypeKind.DECLARED. If that is
the case, cast the Type to DeclaredType and call asElement to get the
element for the type (this removes any resolved generic paramters on the
type) and cast to DeclaredElement (would this ever not be the case?).
Finally use factory.getAnnotatedType(DeclaredElement) to get an
AnnotatedDeclaredType which has the annotation you want (you may also want
to check annotations on inherited types using directSuperTypes()).
On Tue, Sep 16, 2008 at 5:34 AM, David Goodenough <
david.goodenough at linkchoose.co.uk> wrote:
> I am new to this list, and I could not find anything about this when
> scanning the archives.
> I have a need to find the annotations that apply to an object (or rather to
> the definition of that object, rather than finding the annotations that
> to named methods/classes/packages/fields.
> Looking at JSR-308 I see that you have now extended annotations to places
> that are not methods/classes/packages/fields, such as local variables which
> are not fields in classes.
> Reading the JSR-308 document (java-annotation-design.pdf) section C.3 only
> extends the run time annotation only in minor ways, which does not really
> seem to reflect (sorry) the other additions you have made with this JSR.
> I suppose what is needed is a getAnnotation method on Object which would
> find the annotation on wherever this object came from. Alternatively I
> need a
> means to get back to the field/parameter etc that this object came from.
> Has any thought been given to how this might be addresses?
> JSR308 mailing list
> JSR308 at lists.csail.mit.edu
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the JSR308