获取、设置注释的值

示例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;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值