Our Revision annotation type could also be annotated with:
@Target(ElementType.TYPE)
to restrict its applicability to type declarations. If an annotation type has no @Target meta-annotation then it
is applicable anywhere.
Don't confuse the applicability of an annotation type with the accessibility of the annotation type. If an
annotation is public then it can be used anywhere, but its applicability might restrict what elements it can be
applied to. Conversely, you can't apply an annotation if it is inaccessible, even if you are trying to apply it to
the right kind of element. Restricting the applicability of an annotation does not affect its use within other
annotation types. For example, if Revision were restricted to use on local variables (not that it makes
sense), that doesn't stop ClassInfo from having an element of type Revision.
15.5. Retention Policies
Annotations can serve many different purposes and may be intended for different readers. Most of the
annotations you have seen are intended to be read by programmers, or perhaps a development tool. Others,
such as @Deprecated, are intended for the compiler to read. In some cases a tool may need to extract the
annotations from a binary representation of a class, such as to determine how an application should be
deployed. And sometimes annotations will need to be inspected at runtime.
Associated with every annotation type is a retention policy that determines when the annotation can be
accessed. This retention policy is defined by the RetentionPolicy enum, and is controlled by the use of
the Retention meta-annotation. There are three retention policy values:
SOURCE Annotations exist only in the source file, and are discarded by the compiler when producing
a binary representation.
•
CLASS Annotations are preserved in the binary representation of the class, but need not be available
at runtime.
•
RUNTIME Annotations are preserved in the binary representation of the class and must be available at
runtime via the reflection mechanism.
•
The default retention policy is CLASS. Regardless of the retention policy, annotations on local variables are
never available in the binary representation or at runtime. There is no place to store the information in the
binary representation.
The reflection methods for accessing annotations at runtime are discussed in Section 16.2 on page 414. In
essence, for each annotated element, the runtime system creates an object that implements the interface
defined by the annotation type. You get the values of the annotation elements for that program element by
invoking the corresponding method on that object.
15.6. Working with Annotations
Annotations can be very powerful, but they can easily be misused. It is easy to achieve annotation-overload
when the number and verbosity of the annotations totally obscure the code itself. Annotations should be used
sparingly and wisely.