动态修改注解
最近在项目里做数据导出,用到了EasyEexcel,但是表头字段值是动态变化的,去下图,需要修改@ExcelProperty的value值
public Object changeAnnotation(String className, Map<String,Object> maps){
try {
//这里map的key是实体类字段名,value是需要动态修改的注解值
Class<?> name = Class.forName(className);
T instance = (T) name.newInstance();
if (maps.size()>0){
for (String key:maps.keySet()){
Field value = instance.getClass().getDeclaredField(key);
value.setAccessible(true);
//ExcelProperty 是一个注解注解
ExcelProperty apiParam = value.getAnnotation(ExcelProperty.class);
java.lang.reflect.InvocationHandler invocationHandler = Proxy.getInvocationHandler(apiParam);
Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");
memberValues.setAccessible(true);
Map<String, Object> values = (Map<String, Object>) memberValues.get(invocationHandler);
String[] val = (String[]) values.get("value");
System.out.println("------改之前:"+ Arrays.toString(val));
values.put("value", new String[]{maps.get(key).toString()});//修改属性
System.out.println("-----------------");
value.setAccessible(true);
ExcelProperty apiParam1 = (ExcelProperty) value.getAnnotation(ExcelProperty.class);
System.out.println("------改之后:"+ Arrays.toString(apiParam1.value()));
}
}
return instance;
} catch (Exception e) {
e.printStackTrace();
}
return new Object.getClass();
}
调用了上边的方法后直接调用getClass()传给EasyExcel就行