注解-Annotation

 

1.注解定义

注解也称作元数据,它为我们在源码中添加信息提供了一种形式化的方法,供我们在需要的时候读取有用的信息

2.元注解

   元注解就是JDK已经定义好的注解的注解,   Jdk定义的4个标准元注解:

 

 

定义

取值

 

@Target

说明了Annotation所修饰的对象范围

ElementType

 1.CONSTRUCTOR:用于描述构造器

 2.FIELD:用于描述域

 3.LOCAL_VARIABLE:用于描述局部变量

 4.METHOD:用于描述方法

 5.PACKAGE:用于描述包

 6.PARAMETER:用于描述参数

 7.TYPE:用于描述类、接口(包括注解类型) enum声明

@Target(ElementType.TYPE)

public @interface Table {

  public String tableName() default "className";

}

 

@Retention

定义了该Annotation被保留的时间长短

RetentionPoicy

 1.SOURCE:在源文件中有效(即源文件保留)

 2.CLASS:class文件中有效(即class保留)

 3.RUNTIME:在运行时有效(即运行时保留)

 

@Documented

用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化

是一个标记注解,没有成员

 

@Inherited

阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类

是一个标记注解,没有成员

 

 

 

 

3.自定义注解

@interface用来声明一个注解,其中的每一个方法实际上是声明了一个配置参数

法的名称就是参数的名称

返回值类型就是参数的类型(返回值类型只能是基本类型、ClassStringenum

可以通过default来声明参数的默认值。

 

例子一:(单个参数的注解,一般用名称为value,使用的时候不用nama=XXX的方式

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@Documentedpublic @interface FruitName {

    String value() default "";

}

 

例子二:

@Target(ElementType.FIELD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface FruitColor {

  public enum Color{ BULE,RED,GREEN};

           Color fruitColor() default Color.GREEN;

}

 

 

4.通过反射获取注解信息

  (注意,只有RetentionPoicy=RUNTIME的时候才能通过反射获取到

//判断该方法是否包含MyAnnotation注解

method.isAnnotationPresent(MyAnnotation.class)

//获取该方法的MyAnnotation注解实例

MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);

//获取myAnnotation属性值

String[] value1 = myAnnotation.value1();

//获取方法上的所有注解

Annotation[] annotations = method.getAnnotations();

 

猜你喜欢

转载自walklen.iteye.com/blog/2391966