1.11.1Creating Annotations Annotation is created based on the interface. |
|
注解基于接口被创建. 在关键字 interface 前加'@'来声明一个annotation类型. 注解只包含方法声明. 这些方法的行为类似字段. |
// A simple annotation type.
@interface MyAnnotation {
String stringValue();
int intValue();
}
Define new annotation type
- All annotation types automatically extend the Annotation interface.
- Annotation is a super-interface of all annotations.
- It overrides hashCode( ), equals( ), and toString() defined by Object.
- It defines annotationType( ), which returns a Class object that represents the invoking annotation.
- When you apply an annotation, you give values to its members.
// A simple annotation type.
@interface MyAnnotation {
String stringValue();
int intValue();
}
public class MainClass {
// Annotate a method.
@MyAnnotation(stringValue = "Annotation Example", intValue = 100)
public static void myMethod() {
}
}
1.11.3 Specifying a Retention Policy 指定 保留方针
A retention policy determines at what point an annotation is discarded.
- SOURCE: annotation retained only in the source file and is discarded during compilation.
- CLASS: annotation stored in the .class file during compilation, not available in the run time.
- RUNTIME: annotation stored in the .class file and available in the run time.
- They are defined java.lang.annotation.RetentionPolicy enumeration.
A retention policy is specified using Java's built-in annotations: @Retention.
@Retention(retention-policy)
the default policy is CLASS.
MyAnnotation uses @Retention to specify the RUNTIME retention policy.
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// A simple annotation type.
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {
String stringValue();
int intValue();
}
public class MainClass {
// Annotate a method.
@MyAnnotation(stringValue = "Annotation Example", intValue = 100)
public static void myMethod() {
}
}
1.11.4 default values in an annotation 注解中的默认值
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnno {
String str() default "Testing";
int val() default 9000;
}
public class Meta3 {
@MyAnno()
public static void myMeth() {
Meta3 ob = new Meta3();
try {
Class c = ob.getClass();
Method m = c.getMethod("myMeth");
MyAnno anno = m.getAnnotation(MyAnno.class);
System.out.println(anno.str() + " " + anno.val());
} catch (NoSuchMethodException exc) {
System.out.println("Method Not Found.");
}
}
public static void main(String args[]) {
myMeth();
}
}