Java Reflect如何利用反射获取属性上的注解
目录
- 1. AnnotatedElement接口
- 2. Field类实现了AnnotatedElement接口
- 3. 获取属性上的注解
- 总结
1. AnnotatedElement接口
AnnotatedElement接口表示目前正在此 JVM 中运行的程序的一个已注释元素,该接口允许反射性地读取注释。
调用AnnotatedElement对象的如下方法可以访问Annotation信息:
getAnnotation(Class<T>annotationClass):返回该程序元素上存在的指定类型的注释,如果该类型的注释不存在,则返回null。Annotation[] getAnnotations():返回此元素上存在的所有注释。boolean编程 isAnnotationPresent(Class<?extendsAnnotation>annotationClass):判断该程序元素上是否存在指定类型的注释,如果存在则返回true,否则返www.devze.com回false。Annotation[] getDeclaredAnnotations():返回直接存在于此元素上的所有注释。与此接口中的其他方法不同,该方法将忽略继承的注释。
2. Field类实现了AnnotatedElement接口

3. 获取属性上的注解
① 自定义注解
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER} )
public @interface MyParam1 {
String value() default "";
}
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD,ElementType.TYPE,ElementType.FIELD,ElementType.PARAMETER} )
public @interface MyParam2 {
String value() default "";
}
② 给方法参数上添加注解
@ControllerAdvice
@Controller
@MyAnnotation(name = "李四",age=12)
public class Test {
@MyField1("name1")
@MyField2("name2")
@Value("name")
private String name;
@MyField1("email1")
@MyField2("email2")
@Value("email")
private String email;
}
③ 获取属性上的注解
public class Main {
public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException {
// 得到Class类对象
Class<?> clazz = Class.forName("com.example.Redislock.annotation.Test");
// 获取类的所有属性
Field[] fields = clazz.getDeclaredFields();
// 获取属性上的所有注解
int i = 1;
for (Field field : fields) {
System.out.println("第"+i+++"个属性的注解有:");
Annotaandroidtion[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println(annotation.annotationType());
}
}
// 获取属性上指定MyFieandroidld2类型的注解
System.out.println();
System.out.println("获取属性上指定MyField2类型的注解:");
for (Field field : fields) {
MyField2 myField2 = field.getAnnotation(MyField2.class);
System.out.println(myField2);
System.out.println(myField2.value());
}
// 获取属性上指定MyField2类型的注解
System.out.println();
System.out.println("获取属性上指定MyField2类型的注解:");
for (Field field : fields) {
MyField2[] myField2s = field.getAnnotationsByType(MyField2.class);
for (MyField2 myField2 : myField2s) {
System.out.println(myField2)www.devze.com;
}
}
}
}

总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。
加载中,请稍侯......
精彩评论