Java Reference
In-Depth Information
The following declaration of the Version annotation type annotates the annotation type declaration with the
Target meta-annotation, which specifies that the Version annotation type can be used with program elements of
only three types: any type (class, interface, enum, and annotation types), a constructors, and methods.
// Version.java
package com.jdojo.annotation;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
@Target({ElementType.TYPE, ElementType.CONSTRUCTOR, ElementType.METHOD})
public @interface Version {
int major();
int minor();
}
The Version annotation cannot be used on any program elements other than the three types specified in its
Target annotation. The following use of the Version annotation is incorrect because it is being used on an instance
variable (a field):
public class WontCompile {
// A compile-time error. Version annotation cannot be used on a field.
@Version(major = 1, minor = 1)
int id = 110;
}
The following uses of the Version annotation are valid:
// OK. A class type declaration
@Version(major = 1, minor = 0)
public class VersionTest {
// OK. A constructor declaration
@Version(major = 1, minor = 0)
public VersionTest() {
// Code goes here
}
// OK. A method declaration
@Version(major = 1, minor = 1)
public void doSomething() {
// Code goes here
}
}
Prior to Java 8, annotation were allowed on formal parameters of methods and declarations of packages, classes,
methods, fields, and local variables. Java 8 added support for using annotations on any use of a type and on type
parameter declaration. The phrase “any use of a type” needs little explanation. A type is used in many contexts, for
example, after the extends clause as a supertype, in an object creation expression after the new operator, in a cast, in a
throws clause, etc. From Java 8, annotations may appear before the simple name of the types wherever a type is used.
Note that the simple name of the type may be just used as a name, not as a type, for example in an import statement.
Consider the declarations of the Fatal and NonZero annotation types in Listing 1-11 and Listing 1-12.
Search WWH ::




Custom Search