springBoot中获取字段上的注解
时间: 2023-09-15 13:19:41 浏览: 149
在SpringBoot中,可以通过反射获取类的字段上的注解。具体的步骤如下:
1. 获取要反射的类的Class对象,可以使用Class.forName()方法获取。
2. 使用Class对象的getDeclaredFields()方法获取该类的所有字段。
3. 遍历获取到的字段数组,使用Field对象的getAnnotations()方法获取该字段上的所有注解。
4. 判断该注解是否为需要的注解类型,如果是,则获取该注解中的属性值。
下面是一个示例代码:
```java
Class<?> clazz = Class.forName("com.example.demo.User");
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType() == MyAnnotation.class) {
MyAnnotation myAnnotation = (MyAnnotation) annotation;
String value = myAnnotation.value();
System.out.println("字段名:" + field.getName() + ",注解值:" + value);
}
}
}
```
其中,MyAnnotation为自定义的注解类,value()为该注解中的属性。该示例代码可以获取到类中所有字段上的MyAnnotation注解,并输出注解中的属性值。