动态修改注解的值
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
/**
* @Auther: 罗罗
* @Date: 2021/5/3 18:58
* @Description:
*/
@Slf4j
public class ReflectUtils {
public static void setAnnotationValue(Class<?> cls, String cron){
try {
Method declaredMethod = cls.getDeclaredMethod("Methodname ");
Scheduled annotation = declaredMethod.getDeclaredAnnotation(Scheduled.class);
if (annotation == null)
throw new RuntimeException("please add annotation");
//获取 annotation 这个代理实例所持有的 InvocationHandler
InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
// 获取 AnnotationInvocationHandler 的 memberValues 字段
Field field = invocationHandler.getClass().getDeclaredField("memberValues");
field.setAccessible(true);
// 获取 memberValues
Map memberValues = (Map) field.get(invocationHandler);
// 修改注解的属性值
memberValues.put("cron", cron);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}