java修改运行时实体类中属性上面的注解值

工具类
package com.ruoyi.web.controller.tool;

import com.ruoyi.biz.domain.ModelAttribute;
import com.ruoyi.common.annotation.Excel;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

public class JavasistUtils {
    public static Class configClass(Class c, Map<String, ModelAttribute> attributeMap) {
        Field[] fields = c.getDeclaredFields();
        try {
            for (int i = 0; i < fields.length; i++) {
                Field f = fields[i];
                String attributeName = f.getName();
                if (attributeName.startsWith("param_")) {
                    if (attributeMap.containsKey(attributeName)) {
                        String attributeLable = attributeMap.get(attributeName).getAttributeLabel();
                        Excel excelAn = f.getAnnotation(Excel.class);//Excel是注解类型
                        if (excelAn == null) {
                            continue;
                        }
                        InvocationHandler h = Proxy.getInvocationHandler(excelAn);
                        Field hField = h.getClass().getDeclaredField("memberValues");
                        // 因为这个字段是 private 修饰,所以要打开权限
                        hField.setAccessible(true);
                        // 获取 memberValues
                        Map memberValues = (Map) hField.get(h);
                        // 修改 value 属性值 这里修改的是@Excel(name = "姓名")
                        //name是key
                        memberValues.put("name", attributeLable);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return c;
    }
}

调用:

Model model = modelService.selectModelById(article.getModelId());
List<ModelAttribute> attributeList = model.getAttributeList();
Map<String, ModelAttribute> attributeMap = attributeList.stream()
        .collect(Collectors.toMap(ModelAttribute::getAttributeField, v -> v));

List<Article> list = articleService.selectExportArticleByIds(article.getIds());
ExcelUtil<Article> util = new ExcelUtil<Article>(JavasistUtils.configClass(Article.class, attributeMap));
util.exportExcel(response, list, "文章数据");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值