Java Reference
In-Depth Information
// Implemented method from the Version annotation type
@Override
public int minor() {
return 0;
}
// Implemented method from the Annotation annotation type,
// which is the supertype of the Version annotation type
@Override
public Class<? extends Annotation> annotationType() {
return null;
}
}
The Java runtime implements the annotation type to a proxy class. It provides you with an object of a class that
implements your annotation type for each annotation you use in your program. You must distinguish between an
annotation type and instances (or objects) of that annotation type. In your example,
Version
is an annotation type.
Whenever you use it as
@Version(major=2, minor=4)
, you are creating an instance of the
Version
annotation type.
An instance of an annotation type is simply referred to as an
annotation
. For example, we say that
@Version(major=2,
minor=4)
is an annotation or an instance of the
Version
annotation type. An annotation should be easy to use in a
program. The syntax
@Version(...)
is shorthand for creating a class, creating an object of that class, and setting the
values for its elements. I will cover how to get to the object of an annotation type at runtime later in this chapter.
Using Annotations
In this section, I will discuss the details of using different types of elements while declaring annotation types.
Remember that the supplied value for elements of an annotation must be a compile-time constant expression and
you cannot use
null
as the value for any type of element in an annotation.
Primitive Types
The data type of an element in an annotation type could be any of the primitive data types:
byte
,
short
,
int
,
long
,
float
,
double
,
boolean
, and
char
. The
Version
annotation type declares two elements,
major
and
minor
, and both are
of
int
data type. The following code snippet declares an annotation type called
PrimitiveAnnTest
:
public @interface PrimitiveAnnTest {
byte a();
short b();
int c();
long d();
float e();
double f();
boolean g();
char h();
}
You can use an instance of the
PrimitiveAnnTest
type as
@PrimitiveAnnTest(a=1, b=2, c=3, d=4, e=12.34F, f=1.89, g=true, h='Y')