In essence, the elements of an annotation type are like the fields of an object, that is instantiated for each
program element the annotation type is applied to. The values of these fields are determined by the initializers
given when the annotation is applied or by the default value of the element if it has one.
You can give an element a default value by following the empty parameter list with the keyword default
and a suitable value. For example, suppose you want to represent a revision number as a pair of integers for
the major and minor revision, you could define the following annotation type that has a default revision
number of 1.0:
@interface Revision {
int major() default 1;
int minor() default 0;
}
The values themselves must be constant expressions or literals (such as a class literal), but not null.
The Revision annotation type could be used to annotate a class or interfacewe show you how to enforce
this a little lateror used by other annotation types. In particular we can redefine the ClassInfo annotation
type to use it:
@interface ClassInfo {
String created();
String createdBy();
String lastModified();
String lastModifiedBy();
Revision revision();
}
When we first created class Foo we might have used ClassInfo:
@ClassInfo (
created = "Jan 31 2005",
createdBy = "James Gosling",
lastModified = "Jan 31 2005",
lastModifiedBy = "James Gosling",
revision = @Revision
)
public class Foo {
// ...
}
Notice how the initialization expression for an element of an annotation type uses the annotation syntax. In
this case @Revision initializes the revision element with the default values for major and minor. When
Foo is later edited, the revision element would be changed accordingly, for example:
@ClassInfo (
created = "Jan 31 2005",
createdBy = "James Gosling",
lastModified = "Feb 9 2005",
lastModifiedBy = "Ken Arnold",
revision = @Revision(major = 3)
)
public class Foo {
// ...