Java注解之运行时注解
注解的生命周期
- RetentionPolicy.SOURCE 注解只在源代码中,编译成class文件之后,就没了
- RetentionPolicy.CLASS 注解在java文件编译成class文件之后,依然存在,但是运行起来就没有了
- RetentionPolicy.RUNTIME 注解在运行起来之后依然存在,程序可以通过类反射获取这些信息
RetentionPolicy.RUNTIME
这里我们介绍运行时注解
首先建立一个自定义注解
@Retention(RetentionPolicy.RUNTIME)
public @Interface FaceDemo{String value() default "";
}
使用自定义注解
public class FaceTest {
@FaceDemo
public String str ="";
}
创建一个解析器
public class FaceDemoProcessor {
public static void main(String[] args){
Class<?> cls = FaceTest.class;
try{
Field str = cls.getField("str");//获取指定成员属性
boolean b = str.isAnnotationPresent(FaceDemo.class);//这个属性上是否有这个注解
if(b){
//获取所有的注解
Annotation[] annotations = str.getAnnotations();
System.out.println(annotations.length);
//获取指定注解
FaceDemo annotation = str.getAnnotation(FaceDemo.class);
System.out.println(annotation.value());
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
输出
1
自定义运行时注解通过类反射获取注解的几个常用方法
/**
- 获取指定类型的注解
*/
public A getAnnotation(Class annotationType);
/**
- 获取所有注解
*/
public Annotation[] getAnnotations();
/**
- 获取所有注解,忽略继承的注解
*/
public Annotation[] getDeclaredAnnotations();
/**
- 指定注解是否存在该元素上,如果有则返回true,否则false
*/
public boolean isAnnotationPresent(Class<? extends Annotation> annotationType);
/**
- 获取Method中参数的所有注解
*/
public Annotation[][] getParameterAnnotations();
- 获取指定类型的注解
还没有评论,来说两句吧...