Annotation:注解,即为标签,标明某个类/方法/域的特征,然后通过反射来进行获取并处理。
java中提供有几种元注解:元解解就是指标在标解上的注解,注解定义的时候使用到。
1.@Rentention :注解的生命周期,即存在空间。
@Documented
//此注解表明是在运行时生效
@Retention(RetentionPolicy.RUNTIME)
//此注解是注解应用的位置:注解类
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
//注解的属性
RetentionPolicy value();
}
其中属性value:RetentionPolicy.SOURCE(仅存在代码上),
RetentionPolicy.CLASS(参也编译),
RetentionPolicy.RUNTIME(参与运行)
注意value值只能存在一种生命周期:如@Retention(RetentionPolicy.RUNTIME)
2.@Target:注解应用的位置
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
//注意value为数组
ElementType[] value();
}
ElementType[] value(); value值为数组,注解可以同时应用到多种位置,如:
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public enum ElementType {
TYPE, //类
FIELD, //属性
METHOD, //普通方法
PARAMETER, //参数
CONSTRUCTOR, //构造方法
LOCAL_VARIABLE, //本地变量
ANNOTATION_TYPE,//注解类
PACKAGE, //包
TYPE_PARAMETER, //类变量
TYPE_USE
}
3.@Documented:文档注解,java生成api文档
4.@Inherited:继承注解,标注此注解的类的子类自动继承该类的注解。
示例程序:
注:程序运行时只能取得@Target标注为RUNTIME的注解
//自定义注解
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={TYPE,METHOD,FIELD})
@Inherited
@interface MyAnnotation{
String[] value();
int id();
}
@MyAnnotation(id = 1,value = {"A","B"})
class Message {}
//测试方法
public static void main(String[] args) throws Exception {
//是否存在注解
boolean present = MessageImpl.class.isAnnotationPresent(MyAnnotation.class);
if(present){
MyAnnotation annotation = MessageImpl.class.getAnnotation(MyAnnotation.class);
//取出注解的值
String[] value = annotation.value();
int id = annotation.id();
System.out.println(Arrays.toString(value));
System.out.println(id);
}
}