自定义Annotation
定义简单的Annotation
[public] @interface Annotation名称{
数据类型 变量名称();
}
要定义Annotation必须使用@interface的方式进行定义,但从上面可以方法,定义Annotation时候也可以
定义各种变量,但是定义的变量的后面必须使用“()”
使用了@interface就相当于继承了Annotation接口。
实例:使用Annotation
public @interface MyAnnotation{
}
定义了一个Annotation,其中没有定义任何变量,需要定义一个其它的类,并使用@MyAnnotation的形式去
注解
@MyAnnotation
public class Demo{
}
向Annotation设置内容
在Annotation中必须使用变量接收参数。
public @interface MyAnnotation{
public String value();
}
以后在使用Annotation时,可以将内容设置给value
@MyAnnotation("zhangsan")
public class Demo{
}
可以指定接收属性的名称(多个属性的时候):
@MyAnnotation(value="zhangsan")
public class Demo{
}
如果要为一个属性设置多个内容,可以将属性设置为数组
public @interface MyAnnotation{
public String[] value();
}
使用:
@MyAnnotation(value= {"zhangsan","lisi"})
public class Demo{
}
可以为Anntation指定默认值(这样可以不用必须传参数了)
public @interface MyAnnotation{
public String naem() default "xiaoming";
public int age() default 20;
}
@MyAnnotation
public class Demo{
}
可以不用赋值,采用默认值。
Retention和RetentionPolicy
在Annotation,可以使用Retention定义一个Annotation的保存范围。
620