Java Reference
In-Depth Information
METHOD
,
FIELD
,
PARAMETER
and a few more. If more than one is needed, use array initializer
syntax.
AnnotationDemo
also has the
@Retention(RetentionPolicy.RUNTIME)
annotation to re-
quest that it be preserved until runtime. This is obviously required for any annotation that
will be examined by a framework at runtime.
These two meta-annotations are common on user-defined annotations that will be examined
at runtime.
The class
FancyClassJustToShowAnnotation
shows using the
AnnotationDemo
annota-
tion, along with a standard Java one (the
@Resource
annotation).
Refer to
Finding Plug-in-like Classes via Annotations
for a full example of using this mech-
anism.
Finding Plug-in-like Classes via Annotations
Problem
You want to do plug-in-like things without using an explicit plug-in API.
Solution
Define an annotation for the purpose, and use it to mark the plug-in classes.
Discussion
Suppose we want to model how the Java EE standard
javax.annotations.Named
or
javax.faces.ManagedBean
annotations work; for each class that is so annotated, convert
the class name to an instance-like name (e.g, lowercase the first letter), and do something
special with it. You'd want to do something like the following:
1. Get the list of classes in the given package(s) (see
Listing Classes in a Package
).
2. Check if the class is annotated.
3. If so, save the name and
Class
descriptor for later use.