记一次AOP+反射动态修改注解值成功后注解没有生效

本文记录了一次尝试通过AOP和反射动态修改注解值,期望改变@Validated注解行为的过程。尽管在运行时成功修改了注解值,但在实际校验过程中,由于注解值是从.class文件读取,导致修改并未生效。结论是,反射只能查看类结构,无法修改.class文件内容,因此注解的动态修改并未影响校验行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

记一次AOP+反射动态修改注解值成功后注解没有生效

最近重新看了一下反射,突发奇想,在运行的时候在不同的方法上放入不同的注解值,然后获取到注解值进行修改。于是拿了hirbernate的@Validated来玩玩。

我的想法是自定义注解里面@Validated是空的{},然后我们通过获取不同接口(路由)上的@Validation注解值,然后修改进去@Validated里面。

如果看不懂修改注解值,可以参考一下这篇文章。获取出来的Annotation其实是个Proxy对象。https://blog.youkuaiyun.com/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
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值