THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

}


This updates the revision to be 3.0, by specifying the major value and again allowing the minor value to
default to 0.


An annotation type can have zero elements, in which case it is called a marker annotationsimilar to a marker
interface. For example, the annotation type java.lang.Deprecated is a marker annotation that
identifies a program element that should no longer be used. The compiler can issue a warning when a program
element annotated with @Deprecated is used, as could an annotation-aware development environment.


If an annotation type has but a single element, then that element should be named value. This permits some
syntactic shorthand that is described in the next section.


There are further restrictions on the form of an annotation type. An annotation type may not explicitly declare
that it extends another interface, but all annotation types implicitly extend the interface Annotation. An
annotation type is not allowed to be a generic type. Finally, an annotation type is not allowed to directly, or
indirectly, have an element of its own type.[3]


[3] This restriction is aimed at preventing the possibility of infinite recursion if an annotation
type had an element of its own type with a default value. Curiously, there are no attempts to
prevent a similar infinite recursion with class types.

If an interface explicitly extends Annotation it is not an annotation typeand Annotation itself is not an
annotation type. Similarly, if an interface declares that it extends an annotation type, that interface is not itself
an annotation type. Extending or implementing an annotation type is pointless, but if you do it, the annotation
type is just a plain interface with the declared set of methods (including those inherited from Annotation).


Finally, just like any other interface, an annotation type can declare constants and (implicitly static) nested
types.


15.3. Annotating Elements


The program elements that can be annotated are all those for which modifiers can be specified: type
declarations (classes, interfaces, enums, and annotation types), field declarations, method and constructor
declarations, local variable declarations, and even parameter declarations. There is also a special mechanism
to annotate packages, described in Section 18.5 on page 476.


As you have seen, to annotate an element you provide the name of the annotation type being applied, preceded
by @ and followed by a parenthesized list of initializers for each element of the annotation type. A given
program element can only be annotated once per annotation type.


If the annotation type is a marker annotation or if all its elements have default values, then the list of
initializers can be omitted. For example, you can mark a method as deprecated:


@Deprecated
public void badMethod() { / ... / }


Equivalently, you can just specify an empty list of initializers:


@Deprecated()

Free download pdf