Java Reference
In-Depth Information
// Annotation for local variable newValue
@Version(major = 1, minor = 2)
int newValue = xyz;
this.xyz = xyz;
}
}
In Listing 1-2, you use @Version annotation to annotate the class declaration, class field, constructors, and
methods. There is nothing extraordinary in the code for the VersionTest class. You just added the @Version
annotation to various elements of the class. The VersionTest class would work the same, even if you remove all
@Version annotations. It is to be emphasized that using annotations in your program does not change the behavior
of the program at all. The real benefit of annotations comes from reading it during compilation and runtime.
What do you do next with the Version annotation type? You have declared it as a type. You have used it in your
VersionTest class. Your next step is to read it at runtime. Let's defer this step for now; I will cover it in detail in a later
section.
Restrictions on Annotation Types
An annotation type is a special type of interface with some restrictions. I will cover some of the restrictions in the
sections to follow.
Restriction #1
An annotation type cannot inherit from another annotation type. That is, you cannot use the extends clause in an
annotation type declaration. The following declaration will not compile because you have used the extends clause to
declare WrongVersion annotation type:
// Won't compile
public @interface WrongVersion extends BasicVersion {
int extended();
}
Every annotation type implicitly inherits the java.lang.annotation.Annotation interface, which is declared as
follows:
package java.lang.annotation;
public interface Annotation {
boolean equals(Object obj);
int hashCode();
String toString();
Class<? extends Annotation> annotationType();
}
This implies that all of the four methods declared in the Annotation interface are available in all annotation
types. A word of caution needs to be mentioned here. You declare elements for an annotation type using abstract
method declarations. The methods declared in the Annotation interface do not declare elements in an annotation
type. Your Version annotation type has only two elements, major and minor , which are declared in the Version
 
Search WWH ::




Custom Search