Java Reference
In-Depth Information
The Retention Annotation
You can use annotations for different purposes. You may want to use them solely for documentation purposes, to be
processed by the compiler, and/or to use them at runtime. An annotation can be retained at three levels.
•
Source code only
•
Class file only (the default)
•
The
Retention
meta-annotation type is used to specify how an annotation instance of an annotation type should
be retained by Java. This is also known as the
retention policy
of an annotation type. If an annotation type has a
“source code only” retention policy, instances of its type are removed when compiled into a class file. If the retention
policy is “class file only,” annotation instances are retained in the class file, but they cannot be read at runtime. If the
retention policy is “class file and runtime” (simply known as runtime), the annotation instances are retained in the
class file and they are available for reading at runtime.
The
Retention
meta-annotation type declares one element, named
value
, which is of the
java.lang.
annotation.RetentionPolicy
enum type. The
RetentionPolicy
enum has three constants,
SOURCE
,
CLASS,
and
RUNTIME
, which are used to specify the retention policy of source only, class only, and class-and-runtime, respectively.
The following code uses the
Retention
meta-annotation on the
Version
annotation type. It specifies that the
Version
annotations should be available at runtime. Note the use of two meta-annotations on the
Version
annotation type:
Target
and
Retention
.
Class file and the runtime
// Version.java
package com.jdojo.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR,
ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Version {
int major();
int minor();
}
■
if you do not use the
Retention
meta-annotation on an annotation type, its retention policy defaults to class file
only. this implies that you will not be able to read those annotations at runtime. You will make this common mistake in
the beginning. You would try to read annotations and the runtime will not return any values. Make sure that your annotation
type has been annotated with the
Retention
meta-annotation with the retention policy of
RetentionPolicy.RUNTIME
before you attempt to read them at runtime. an annotation on a local variable declaration is never available in the class
file or at runtime irrespective of the retention policy of the annotation type. the reason for this restriction is that the Java
runtime does not let you access the local variables using reflection at runtime, and unless you have access to the local
variables at runtime, you cannot read annotations for them.
Tip