Java Reference
In-Depth Information
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 element-
consider applying
ClassInfo
to a method parameter! You can restrict the
applicability of an annotation type by annotating it with the
@Target
an-
notation. An annotation on an annotation type is known as a
meta-an-
notation.
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 annota-
tion types, and controls where those types are themselves applicable. It
has a single elementan array of the enum type
ElementType
which follow-
ing 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 pro-
gram element.
The
ClassInfo
annotation type should only be applied to type declarations
(classes, interfaces, enums, or annotation types), so it should be de-
clared:
@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.