Java Reference
In-Depth Information
Note
Java has always supported ad hoc annotation mechanisms. For example, the
java.lang.Cloneable
interface identifies classes whose instances can be shal-
lowlyclonedvia
Object
's
clone()
method,the
transient
reservedwordmarks
precated javadoc
tag documents methods that are no longer supported. Java 6
formalized the need for annotations by introducing the annotations language feature.
Discovering Annotations
An
annotation
isaninstanceofanannotationtypeandassociatesmetadatawithanap-
plicationelement.Itisexpressedinsourcecodebyprefixingthetypenamewiththe
@
symbol. For example,
@Readonly
is an annotation and
Readonly
is its type.
Note
Youcanuseannotationstoassociatemetadatawithconstructors,fields,local
variables, methods, packages, parameters, and types (annotation, class, enum, and in-
terface).
Thecompilersupportsthe
Override
,
Deprecated
,
SuppressWarnings
,and
SafeVarargs
annotationtypes.Thesetypesarelocatedinthe
java.lang
package.
@Override
annotationsareusefulforexpressingthatasubclassmethodoverrides
a method in the superclass, and does not overload that method instead. The following
example reveals this annotation being used to prefix the overriding method:
@Override
public void draw(int color)
{
// drawing code
}
@Deprecated
annotationsareusefulforindicatingthatthemarkedapplicationele-
mentis
deprecated
(phasedout)andshouldnolongerbeused.Thecompilerwarnsyou
when a deprecated application element is accessed by ondeprecated code.
Incontrast,the
@deprecated javadoc
tagandassociatedtextwarnsyouagainst
using the deprecated item, and tells you what to use instead. The following example
demonstrates that
@Deprecated
and
@deprecated
can be used together:
/**
* Allocates a <code>Date</code> object and initializes it
so that