Java Reference
In-Depth Information
Usage of annotations with an existing framework requires consulting their documentation.
Using annotations for your own purpose at runtime requires use of the Reflection API, as
shown in
Example 23-18
.
One more thing to note about annotations is that they may have attributes. These are defined
as methods in the annotation source code, but used as attributes where the annotation is used.
Example 23-18
is an annotated annotation with one such attribute:
Example 23-18. Annotation demo
/**
* A sample annotation for types (classes, interfaces);
* it will be available at run time.
*/
@Target
(
ElementType
.
TYPE
)
@Retention
(
RetentionPolicy
.
RUNTIME
)
public
public
@interface
AnnotationDemo
{
public
public
boolean
boolean
fancy
()
default
default false
false
;
public
public
int
int
order
()
default
default
42
;
}
/** A simple example of using the annotation */
@AnnotationDemo
(
fancy
=
true
true
)
@Resource
(
name
=
"Dumbledore"
)
class
class
FancyClassJustToShowAnnotation
FancyClassJustToShowAnnotation
{
/** Print out the annotations attached to this class */
public
public static
void
main
(
String
[]
args
) {
Class
<?>
c
=
FancyClassJustToShowAnnotation
.
class
;
System
.
out
.
println
(
"Class "
+
c
.
getName
() +
" has these annotations:"
);
for
static
void
for
(
Annotation a
:
c
.
getAnnotations
()) {
iif
(
a
instanceof
instanceof
AnnotationDemo
) {
AnnotationDemo ad
= (
AnnotationDemo
)
a
;
System
.
out
.
println
(
"\t"
+
a
+
" with fancy="
+
ad
.
fancy
() +
" and order "
+
ad
.
order
());
}
else
else
{
System
.
out
.
println
(
"\tSomebody else's annotation: "
+
a
);
}
}
}
}
AnnotationDemo
has the meta-annotation
@Target(ElementType.TYPE)
to indicate that it
can annotate user-defined types (such as classes). Other
ElementType
choices include