通过反射动态修改注解元素value

修改jackson的JsonIgnoreProperties注解元素值

JsonIgnoreProperties jsonIgnoreProperties = entity.getClass().getAnnotation(JsonIgnoreProperties.class)
if(jsonIgnoreProperties){
    InvocationHandler invocationHandler = Proxy.getInvocationHandler(jsonIgnoreProperties)
    Field field = invocationHandler.class.getDeclaredField("memberValues")

**因为memberValues元素是private final修饰的,需要打开权限**

    field.setAccessible(true); 
    Map fields = field.get(invocationHandler) as Map 
    String[] values = fields.get("value") 
    if(values){ 
            String[] newValues = [] 
            values.each { val -> 
            try { 
                 if(entity.getClass().getDeclaredField(val).type == entity){ 
                      newValues << val 
                 } 
            }catch (NoSuchFieldException e)
                 { log.error("${entity}没有此属性${val}") } 
            } 

    fields.put("value",newValues) 
    }
}


**改完可以new一个实例看看效果**

JsonIgnoreProperties testJsonIgnoreProperties = new TestEntity().getClass().getAnnotation(JsonIgnoreProperties.class)
if(testJsonIgnoreProperties) {
    InvocationHandler handler = Proxy.getInvocationHandler(testJsonIgnoreProperties)
    Field testField = handler.class.getDeclaredField("memberValues")
    testField.setAccessible(true);
    Map fields = testField.get(handler) as Map
    String[] testVal = fields.get("value")
    log.info("测试 ${testVal}")
}

操作有风险,下手需谨慎啊

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值