Java Reference
In-Depth Information
All default values must be compile-time constants. How do you specify the default value for an array type? You
need to use the array initializer syntax. The following snippet of code shows how to specify default values for an array
and other data types:
// Shows how to assign default values to elements of different types
public @interface DefaultTest {
double d() default 12.89;
int num() default 12;
int[] x() default {1, 2};
String s() default "Hello";
String[] s2() default {"abc", "xyz"};
Class c() default Exception.class;
Class[] c2() default {Exception.class, java.io.IOException.class};
}
The default value for an element is not compiled with the annotation. It is read from the annotation type
definition when a program attempts to read the value of an element at runtime. For example, when you use
@Version(major=2) , this annotation instance is compiled as is. It does not add minor element with its default value
as zero. In other words, this annotation is not modified to @Version(major=2, minor=0) at the time of compilation.
However, when you read the value of the minor element for this annotation at runtime, Java will detect that the value
for the minor element was not specified. It will consult the Version annotation type definition for its default value
and return the default value. The implication of this mechanism is that if you change the default value of an element,
the changed default value will be read whenever a program attempts to read it, even if the annotated program was
compiled before you changed the default value.
Annotation Type and Its Instances
I use the terms “annotation type” and “annotation” frequently. Annotation type is a type like an interface.
Theoretically, you can use annotation type wherever you can use an interface type. Practically, we limit its use only
to annotate program elements. You can declare a variable of an annotation type as shown:
Version v = null; // Here, Version is an annotation type
Like an interface, you can also implement an annotation type in a class. However, you are never supposed to do
that, as it will defeat the purpose of having an annotation type as a new construct. You should always implement an
interface in a class, not an annotation type. Technically, the code in Listing 1-3 for the DoNotUseIt class is valid. This is
just for the purpose of demonstration. Do not implement an annotation in a class even if it works.
Listing 1-3. A Class Implementing an Annotation Type
// DoNotUseIt.java
package com.jdojo.annotation;
import java.lang.annotation.Annotation;
public class DoNotUseIt implements Version {
// Implemented method from the Version annotation type
@Override
public int major() {
return 0;
}
 
Search WWH ::




Custom Search