MyAnnotation1.class
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation1 {
String value();
}
MyAnnotation2.class
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation2 {
String description() default "abcde";
boolean isAnnotation();
}
AnnotationDemo.class@MyAnnotation1("this is annotation1")
public class AnnotationDemo {
@MyAnnotation2(description = "this is annotation2", isAnnotation = true)
public void sayHello() {
System.out.println("hello world!");
}
}
TestAnnotation.classpublic class TestAnnotation {
public static void main(String[] args) throws NoSuchMethodException {
Class<?> cls = new AnnotationDemo().getClass();
MyAnnotation1 myAnnotation1 = cls.getAnnotation(MyAnnotation1.class);
System.out.println(myAnnotation1.value());
MyAnnotation2 myAnnotation2 = cls.getMethod("sayHello").getAnnotation(MyAnnotation2.class);
System.out.println(myAnnotation2.description());
System.out.println(myAnnotation2.isAnnotation());
MyAnnotation2 myAnnotation22 = cls.getMethod("sayHi",String.class).getAnnotation(MyAnnotation2.class);
System.out.println(myAnnotation22.description());
System.out.println(myAnnotation22.isAnnotation()); }
}
運行程序,打印結果:
this is annotation1
this is annotation2
true
abcde
false
分析:
1. MyAnnotation1中的@Target(ElementType.TYPE)
@Target裏面的ElementType是用來指定Annotation類型可以用在哪些元素上的.例如:
TYPE(類型)、FIELD(屬性)、METHOD(方法)、PARAMETER(參數)、CONSTRUCTOR(構造函數)、LOCAL_VARIABLE(局部變量),、PACKAGE(包),其中的TYPE(類型)是指可以用在Class,Interface,Enum和Annotation類型上。
2. MyAnnotation1中的@Retention(RetentionPolicy.RUNTIME)
RetentionPolicy 共有三種策略,分別爲:
SOURCE:這個Annotation類型的信息只會保留在程序源碼裏,源碼如果經過了編譯之後,Annotation的數據就會消失,並不會保留在編譯好的.class文件裏面
CLASS:這個Annotation類型的信息保留在程序源碼裏,同時也會保留在編譯好的.class文件裏面,在執行的時候,並不會把這些信息加載到JVM中。注:默認策略爲CLASS類型
RUNTIME:表示在源碼、編譯好的.class文件中保留信息,在執行的時候會把這一些信息加載到JVM中去的
3. MyAnnotation1中的@Documented
目的就是將這一Annotation的信息顯示在JAVA API文檔上,如果沒有增加@Documented的話,JAVA API文檔上不會顯示相關annotation信息