annotation的汉语意思是:注解,注释
它是一种特殊的类,类似于接口,定义方法:
public @interface MyAnnotation{
//代码
}
annotation前面还可以加上注解,如
加上@Retention(RetentionPolicy.RUNTIME)
表示这个annotation保留到什么状态,有三种状态:
RetentionPolicy.SOURCE 表示只保留在源文件
RetentionPolicy.CLASS 表示保留到CLASS文件
RetentionPolicy.RUNTIME 表示保留到运行期
加上@Target({ElementType.METHOD,ElementType.TYPE})
表示annotation可以用的位置,可以在方法,参数,类等等上定义
在annotation内可以定义属性
比如:String color();
int value();
设置默认值方式:String color() default "blue";
属性的类型可以是基本型,String,Class,数组,枚举,注解这些类型.
annotation的调用方法:
在需要使用的方法,类等等前面加上@MyAnnotation(color="red",value=3)
如果只有一个value属性,或者其它属性都有默认值,则在引用注解时,可以省略"value=",直接写为@MyAnnotation(3)
如果属性类型为数组,且数组中只有一个元素,则可以省略中括号
比如有属性int[] arrAt();调用时如果只有一个元素,则可表示为:@MyAnnotation(arrAt=1)
以上