Java Reference
In-Depth Information
16.2. Annotation Queries
You can ask about the annotations applied to a class or interface using
methods that are similar to those used for asking about members, but
which differ slightly in the details. These methods are all part of the
AnnotatedElement interface. AnnotedElement is implemented by all the re-
flection classes that represent program elements: Class , Field , Method ,
Constructor , and Package . The discussion here applies to all these Annot-
atedElement instances.
The annotation queries can only provide information on those annota-
tions that are available at runtimethat is, those annotations with a re-
tention policy of RetentionPolicy.RUNTIME (see " Retention Policies " on page
395 ) .
You can ask for all the annotations present on an element, whether de-
clared directly or inherited, by using getAnnotations , which returns an ar-
ray of Annotation instances. Or you can ask for only the directly applied
annotations using geTDeclaredAnnotations , which also returns an array of
Annotation instances. You can ask for a specific annotation using getAn-
notation , which takes the type of the annotation as an argument and re-
turns the Annotation object or null if it is not present. You can ask wheth-
er a specific annotation type is present on an element using the boolean-
isAnnotationPresent method. In contrast to the similarly named methods
for querying members, there is no notion of public versus non-public an-
notations, and also no security checks.
The annotation instances that are returned are proxy objects that imple-
ment the interface defined by a given annotation type. The methods of
the annotation type can be invoked to obtain the annotation values for
each annotation element. For example, assuming our BugsFixed annota-
tion type (see page 392 ) had a runtime retention policy, then given
@BugsFixed( { "457605", "532456"} )
class Foo { /* ... */ }
 
Search WWH ::




Custom Search