记一次AOP+反射动态修改注解值成功后注解没有生效
最近重新看了一下反射,突发奇想,在运行的时候在不同的方法上放入不同的注解值,然后获取到注解值进行修改。于是拿了hirbernate的@Validated来玩玩。
我的想法是自定义注解里面@Validated
是空的{},然后我们通过获取不同接口(路由)上的@Validation
注解值,然后修改进去@Validated
里面。
如果看不懂修改注解值,可以参考一下这篇文章。获取出来的Annotation其实是个Proxy对象。https://blog.csdn.net/qq_39309348/article/details/110455235
上代码。
自定义注解
@Target({
ElementType.PARAMETER,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Validated
public @interface Validation {
Class<?>[] value() default {
};
interface PutGroup {
}
interface DeleteGroup {
}
interface ModifyGroup {
}
interface QueryGroup {
}
interface UpdateGroup extends DeleteGroup, ModifyGroup {
}
}
这是Test类
@Data
public class Test {
@NotNull(groups = {
Validation.DeleteGroup.class})
String a;
@NotNull(groups = {
Validation.DeleteGroup.class,Validation.ModifyGroup.class})
String b;
@NotNull(groups = {
Validation.ModifyGroup.class})
String c;
}
这是测试接口
@RequestMapping("/test")
@SuppressWarnings("unchecked")
public String test(@Validation(Validation.ModifyGroup.class) Test test) throws NoSuchFieldException, IllegalAccessException, NoSuchMethodException {
// 这里通过反射获取到@Validation注解里面@Validated的注解值
Method method = TestController.class.getMethod("test", Test.class);
int parameterCount = method.getParameterCount();
Annotation[][] pas = method.getParameterAnnotations();
tag:
for (int i = 0; i < parameterCount; i++) {
for (Annotation annotation : pas[i]) {
//判断注解是否为指定类型
InvocationHandler ih = Proxy.getInvocationHandler(annotation);
Field type = ih.getClass().getDeclaredField("type");
type.setAccessible(true);
Class<Validation> clazz = (Class<Validation>) type.get(ih);
String name = clazz.getName();
String validationName = Validation.class