Java Reference
In-Depth Information
The key to writing custom annotations is the use of “meta-
annotations.” These are special annotations, which appear as
annotations on the definition of new (custom) annotation
types.
The meta-annotations are defined in
java.lang.annotation
and allow the devel‐
oper to specify policy for where the new annotation type is to be used, and how it
will be treated by the compiler and runtime.
There are two primary meta-annotations that are both essentially required when
creating a new annotation type—
@Target
and
@Retention
. These both take values
that are represented as enums.
The
@Target
meta-annotation indicates where the new custom annotation can be
legally placed within Java source code. The enum
ElementType
has the following
possible values:
TYPE
,
FIELD
,
METHOD
,
PARAMETER
,
CONSTRUCTOR
,
LOCAL_VARIABLE
,
ANNOTATION_TYPE
,
PACKAGE
,
TYPE_PARAMETER
, and
TYPE_USE
.
The other meta-annotation is
@Retention
, which indicates how
javac
and the Java
runtime should process the custom annotation type. It can have one of three values,
which are represented by the enum
RetentionPolicy
:
SOURC
Annotations with this retention policy are discarded by
javac
during
compilation.
CLAS
This means that the annotation will be present in the class file, but will not nec‐
essarily be accessible at runtime by the JVM. This is rarely used, but is some‐
times seen in tools that do offline analysis of JVM bytecode.
RUNTIME
This indicates that the annotation will be available for user code to access at
runtime (by using reflection).
Let's take a look at an example, a simple annotation called
@Nickname
, which allows
the developer to define a nickname for a method, which can then be used to find the
method reflectively at runtime:
@Target
(
ElementType
.
METHOD
)
@Retention
(
RetentionPolicy
.
RUNTIME
)
public
@interface
Nickname
{
String
[]
value
()
default
{};
}
This is all that's required to define the annotation—a syntax element where the
annotation can appear, a retention policy, and the name of the element. As we need
to be able to state the nickname we're assigning to the method, we also need to