【java反射修改注解属性】java 通过反射,动态修改注解的某个属性值
有些情况为了偷懒,往往会使用注解来动态处理一些功能,比如Excel的导入以及导出等。但是一些情况下我们需要动态的修改注解的属性值,来完成一些特定场景的业务需求。
java动态修改注解的属性代码
public void updateFieldAnnotationVal(String fieldName, String annoName, Class className, Object value ,Class annotation) throws Exception{Field field = className.getDeclaredField(fieldName);//获取属性上面的注解Annotation annotation1 = field.getAnnotation(annotation);//获取动态代理对象InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation1);//获取 AnnotationInvocationHandler 的 memberValues 字段Field memberValues = invocationHandler.getClass().getDeclaredField("memberValues");//由于属性私有,必须打开权限memberValues.setAccessible(true);//修改属性值Map map = (Map) memberValues.get(invocationHandler);map.put(annoName, value);}
调用代码
@GetMapping("/studentMajor/getStudentMajorExcelTemplate")public void getStudentMajorExcelTemplate(StudentMajorVo param, PageRequestVo pageRequestVo) throws Exception {HashMap<String, String[]> boxMap = new HashMap<>();Integer userType = param.getUserType();if (UserType.SCHOOL == userType) {this.updateFieldAnnotationVal("majorId", "importField", StudentMajorExcel.class, false, Excel.class);this.updateFieldAnnotationVal("schoolName", "importField", StudentMajorExcel.class, false, Excel.class);}if (UserType.DEPARTMENT == userType) {this.updateFieldAnnotationVal("majorId", "importField", StudentMajorExcel.class, true, Excel.class);this.updateFieldAnnotationVal("schoolName", "importField", StudentMajorExcel.class, true, Excel.class);}ExcelsUtil.exportCommonTemplate(StudentMajorExcel.class, boxMap);}