Java Reference
In-Depth Information
The return type of Class needs a little explanation. Instead of the Class type, you can use a generic return type
that will return a user-defined class type. Suppose you have a Test class and you want to declare the return type of a
method in an annotation type of type Test . You can declare the annotation method as shown:
public @interface GoodOne {
Class element1(); // Any Class type
Class<Test> element2(); // Only Test class type
Class<? extends Test> element3(); // Test or its subclass type
}
Restriction #5
An annotation type cannot declare a method, which would be equivalent to overriding a method in the Object class
or the Annotation interface.
Restriction #6
An annotation type cannot be generic.
Default Value of an Annotation Element
The syntax for an annotation type declaration lets you specify a default value for its elements. You are not required to
specify a value for an annotation element that has a default value specified in its declaration. The default value for an
element can be specified using the following general syntax:
<modifiers> @interface <annotation type name> {
<data-type> <element-name>() default <default-value>;
}
The keyword default is used to specify the default value. The default value must be of the type compatible to the
data type for the element.
Suppose you have a product that is not frequently released, so it is less likely that it will have a minor version
other than zero. You can simplify your Version annotation type by specifying a default value for its minor element
as zero, as shown:
public @interface Version {
int major();
int minor() default 0; // Set zero as default value for minor
}
Once you set the default value for an element, you do not have to pass its value when you use an annotation of
this type. Java will use the default value for the missing value of the element.
@Version(major=1) // minor is zero, which is its default value
@Version(major=2) // minor is zero, which is its default value
@Version(major=2, minor=1) // minor is 1, which is the specified value
 
Search WWH ::




Custom Search