Java Reference
In-Depth Information
Compile the Example 23-16 with javac and you'll see there's a new MyToyAnnotation.class
file. In Example 23-17 , we examine this with javap , the standard JDK class inspection tool.
Example 23-17. Running javap on trivial annotation
$ javap lang.MyToyAnnotation
Compiled from "MyToyAnnotation.java"
public interface lang.MyToyAnnotation extends java.lang.annotation.Annotation {
}
$
As it says, an Annotation is represented in the class file format as just an interface that ex-
tends Annotation (to answer the obvious question, you could write simple interfaces this
way, but it would be a truly terrible idea). Let's have a quick look at Annotation itself:
$ javap java.lang.annotation.Annotation
Compiled from "Annotation.java"
public interface java.lang.annotation.Annotation {
public abstract boolean equals(java.lang.Object);
public abstract int hashCode();
public abstract java.lang.String toString();
public abstract java.lang.Class<? extends java.lang.annotation.Annotation>
annotationType();
}
$
Annotations can be made such that the compiler will only allow them in certain points in
your code. Here is one that can only go on classes or interfaces:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
}
The @Target specifies where the annotation can be used: ElementType.TYPE makes it us-
able on classes, interfaces, class-like things such as enums, even annotations! To restrict it to
use just on annotations, there is ElementType.ANNOTATION_TYPE . Other types include
METHOD , FIELD , CONSTRUCTOR , LOCAL_VARIABLE , PACKAGE , and PARAMETER . So, this annota-
tion is itself annotated with two @ANNOTATION_TYPE -targeted annotations.
Search WWH ::




Custom Search