Datasheet
{
ProgramFlags flag = ProgramFlags.showErrors;
System.out.println(“Flag selected is: “ +
flag.ordinal() +
“ which is “ +
flag.name());
}
}
The ordinal() method returns the position of the constant in the list. The value of showErrors is 0
because it comes first in the list, and the ordinal values are 0-based. The
name() method can be used to
get the name of the constant, which provides for getting more information about enumerations.
Metadata
Another feature that Sun has decided to include in the JDK 5 release of Java is a metadata facility. This
enables tagging classes with extra information that tools can analyze, and also applying certain blocks
of code to classes automatically. The metadata facility is introduced in the
java.lang.annotation
package. An annotation is the association of a tag to a construct in Java such as a class, known as a target
in annotation terminology. The types of constructs that can be annotated are listed in the
java.lang
.annotation.ElementType
enumeration, and are listed in the following table. Even annotations can
be annotated.
TYPE covers classes, interfaces, and enum declarations.
ElementType Constant
ANNOTATION_TYPE
CONSTRUCTOR
FIELD
LOCAL_VARIABLE
METHOD
PACKAGE
PARAMETER
TYPE
Another concept introduced is the life of an annotation, known as the retention. Certain annotations may
only be useful at the Java source code level, such as an annotation for the
javadoc tool. Others might be
needed while the program is executing. The
RetentionPolicy enumeration lists three type lifetimes
for an annotation. The
SOURCE policy indicates the annotations should be discarded by the compiler, that
is, should only available at the source code level. The
CLASS policy indicates that the annotation should
appear in the class file, but is possibly discarded at runtime. The
RUNTIME policy indicates the annota-
tions should make it through to the executing program, and these can then be viewed using reflection.
26
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 26