注解Annotation

来源:互联网 发布:淘宝购物货到付款 编辑:程序博客网 时间:2024/05/21 17:44

1.什么是Annotation

java.lang.annotation,接口 Annotation。对于Annotation,是Java5的新特性,JDK5引入了Metadata(元数据)很容易的就能够调用Annotations。Annotation实际上表示的是一种注释的语法,使得配置与代码相结合。

以下是Annotation接口定义:

public interface Annotation {    boolean equals(Object obj);     int hashCode();    String toString();    Class<? extends Annotation> annotationType();}

2.jdk自带的三个Annotation

  • @Overrider 明确要覆盖的父类方法,若此方法不存在则会报错。
 public class AnnotationDemo extends Demo{    @Override    public void print(){        System.out.println("这是一个AnnotationDemo");    }}class Demo{    public void print(){        System.out.println("这是一个Demo");    }}
  • @Deprecated 表示过时的或者不建议使用的api,若是使用则会报出警告
    @Deprecated    public int getResult(){        return 0;    }
  • @SuppressWarnings 用于压制警告,若是注释的api范围内存在警告则可以压制告警,但是需要填写需要压制的报警类型,若存在多个警告,可以通过配置数组形式进行压制。
    @SuppressWarnings("deprecated")    public void printResult(){        System.out.println(getResult());    }

3.自定义Annotation

格式如下:

public @interface MyAnnotation {}@MyAnnotationclass Info{}

在一个Annotation中也可以定义多个属性:

public @interface MyAnnotation {    public String key();    public String value();}@MyAnnotation(key="my",value = "Anntotation")class Info{}

若是想为Annotation设置默认值可以使用default关键字

public @interface MyAnnotation {    public String key() default "default_key";    public String value() default "default_value";}@MyAnnotationclass Info{}

如果想要限制Annotation属性的取值范围,可以使用枚举

public @interface MyAnnotation {    public String key() default "default_key";    public String value() default "default_value";    public Color color() default Color.RED;}@MyAnnotation(color = Color.BLUE)class Info{}enum Color{    RED,GREEN,BLUE;}
  • Retention注解说明,这种类型的注解会被保留到那个阶段. 有三个值:
    1.RetentionPolicy.SOURCE —— 这种类型的Annotations只在源代码级别保留,编译时就会被忽略
    2.RetentionPolicy.CLASS —— 这种类型的Annotations编译时被保留,在class文件中存在,但JVM将会忽略
    3.RetentionPolicy.RUNTIME —— 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用
  • Documented 注解 表明这个注解应该被 javadoc工具记录.
  • Inherited 注解 如果定义注解时使用了 @Inherited 标记,然后用定义的注解来标注另一个父类, 父类又有一个子类(subclass),则父类的所有属性将被继承到它的子类中.

4.Annotation与反射机制

注解若想取得作用,必然需要结合反射机制实现其意义。通过反射可以取得属性、方法、构造方法以及类上的所有@Retention值为RetentionPolicy.RUNTIME的注解内容。在Filed、Method、Construct、Class类中全部实现了AnnotatedElement接口,通过Annotation[] getAnnotations();
方法便可以获取。其API如下:
这里写图片描述

@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    public String key() default "default_key";    public String value() default "default_value";}@MyAnnotationclass Info extends Thread{    @Override    @Deprecated    @SuppressWarnings({"deprecated","unused"})    @MyAnnotation    public void run() {        List list = new ArrayList();    }}

测试如下:

    @Test    public void test1() throws NoSuchMethodException {        Class cs = Info.class;        //获取run方法对象        Method method = cs.getMethod("run");        //获取run方法上注解,注意只能得到@Retention值为RetentionPolicy.RUNTIME的注解        Annotation[] annotations = method.getAnnotations();        for(Annotation an : annotations){            System.out.println(an.toString());            //判断是否是指定Annotation        }        //判断是否包含指定Annotation        if(method.isAnnotationPresent(MyAnnotation.class)){            //获取指定Annotation            MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);            //获取Annotation的属性            String key = myAnnotation.key();            String value = myAnnotation.value();            System.out.println(key+" --> "+value);        }    }

这里写图片描述

5.Annotation的使用范围

默认情况下一个自定义的Annotation可以在任何方法、属性以及类上使用。若想限定Annotation的使用范围可以使用@Target注解。

@Target(ElementType.ANNOTATION_TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {    public String key() default "default_key";    public String value() default "default_value";}
ElementType的取值 注解使用范围 METHOD 可用于方法上 TYPE 可用于类或者接口上 ANNOTATION_TYPE 可用于注解类型上(被@interface修饰的类型) CONSTRUCTOR 可用于构造方法上 FIELD 可用于域上 LOCAL_VARIABLE 可用于局部变量上 PACKAGE 用于记录java文件的package信息 PARAMETER 可用于参数上
原创粉丝点击