[JSR308] Runtime access to JSR-308 annotations
mernst at csail.mit.edu
Tue Sep 16 14:53:49 EDT 2008
Artemus Harper gave some feedback about specific techniques you can use for
traversing the AST during type-checking. I want to add a reply in case you
were asking a different question, about reflection at run-time.
> 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 apply
> to named methods/classes/packages/fields.
In Java, there is no run-time representation of the types of the variables
that have previously referred to an object. JSR 308 enriches types, but it
does not change that fundamental property.
Consider the following code.
Number n = new Integer(22);
Object o = n;
If you asked for the type of the object that is pointed to by "o", would
you expect a different answer than that for the object that is pointed to
by "n"? The class of that object can be queried -- it is Integer -- but
that's not the declared type of either of the variables that refers to it.
More generally, Java doesn't maintain a run-time representation of types.
If you wanted to add such a representation, you could do so, but JSR 308
doesn't impose that run-time burden on all Java programs. Its type
annotations are intentionally designed to be implementable without any
> 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
An object may come from many fields/parameters, so I'm not sure which one
you mean. The most recent? The first variable that referred to the
variable? Unless you are asking about the declaration of a variable as
opposed to anything about objects, in which case Artemus's answer is to the
Perhaps an example of what you want to do would help in clearing up the
confusion arising from your question.
> 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.
Can you give an example here, too?
More information about the JSR308