示例1:通过反射获取@ApiModelProperty的value值
import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
public class Main {
public static void main(String[] args) throws Exception {
// 获取目标类的Class对象
Class<?> targetClass = User.class;
// 获取目标字段的Field对象
Field field = targetClass.getDeclaredField("height");
// 获取ApiModelProperty注解
ApiModelProperty annotation = field.getAnnotation(ApiModelProperty.class);
// 获取value属性的值
String value = annotation.value();
// 打印value属性值
System.out.println(value);
}
}
class User {
@ApiModelProperty(value = "身高")
private String height;
}
示例2:更新@ApiModelProperty的value值为"身高(cm)"
import io.swagger.annotations.ApiModelProperty;
import java.lang.reflect.Field;
public static void main(String[] args) throws Exception {
// 获取User类的Class对象
Class<User> clazz = User.class;
// 获取height字段
Field field = clazz.getDeclaredField("height");
// 获取字段上的ApiModelProperty注解
ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
// 获取注解的InvocationHandler
InvocationHandler invocationHandler = Proxy.getInvocationHandler(apiModelProperty);
// 获取InvocationHandler中的memberValues字段
Field annotationField = invocationHandler.getClass().getDeclaredField("memberValues");
// 设置字段可访问
annotationField.setAccessible(true);
// 获取memberValues的值
Map<String, Object> map = (Map<String, Object>) annotationField.get(invocationHandler);
// 修改注解的value属性值
map.put("value", "身高cm");
// 打印修改后的注解值
System.out.println(apiModelProperty.value());
}
@Data
static class User {
@ApiModelProperty(value = "身高")
private String height;
}