Annotation入门

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.class

public 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信息

发布了23 篇原创文章 · 获赞 6 · 访问量 4万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章