THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

You can have more than one element in the annotation type and still call one of them value. If you do, and
all other elements have default values, then you can still use the shorthand form to initialize the value
element. However, once you have more than one initializer expression, you must explicitly name each
element.


Finally, you can annotate an annotation type with itself. For example, the Documented marker annotation
indicates that the program element that is annotated should have its documentation comments processedsee
Chapter 19. Because Documented should itself be documented it is annotated with itself:


@Documented
@interface Documented { }


Self-annotation is quite different from having an element of the annotation type within the annotation
typewhich, as you know, is not permitted.


15.4. Restricting Annotation Applicability


Annotations can appear anywhere a modifier is allowed, but as you can imagine, not every annotation makes
sense for every program elementconsider applying ClassInfo to a method parameter! You can restrict the
applicability of an annotation type by annotating it with the @Target annotation. An annotation on an
annotation type is known as a meta-annotation.


The Target annotation type is one of a small number of annotation types defined in the
java.lang.annotation packageall the types mentioned here are in that package unless otherwise
stated. Target is applied to annotation types, and controls where those types are themselves applicable. It
has a single elementan array of the enum type ElementTypewhich following convention is called value.
ElementType represents the different kinds of program elements to which annotations can be applied, and
defines the constants ANNOTATION_TYPE, CONSTRUCTOR, METHOD, FIELD, LOCAL_VARIABLE,
PARAMETER, PACKAGE, and TYPE. The compiler will check that any annotation applied to a program
element is allowed to be applied to that kind of program element.


The ClassInfo annotation type should only be applied to type declarations (classes, interfaces, enums, or
annotation types), so it should be declared:


@Target(ElementType.TYPE)
@interface ClassInfo {
String created();
String createdBy();
String lastModified();
String lastModifiedBy();
Revision revision();
}


Now if you tried to annotate a parameter declaration with ClassInfo, you'd get a compile-time error.


You can specify multiple element types when applying the Target annotation. For example, an annotation
type that only applies to fields or local variables would be annotated with


@Target({ ElementType.FIELD, ElementType.LOCAL_VARIABLE })

Free download pdf