通过spring aop去反射目标类方法参数的注解值

本文介绍了如何在Spring AOP环境下配置并利用反射技术获取目标类方法参数上的注解值。通过切入点定位到特定方法,接着通过AOP的point参数获取目标类,并进一步反射获取注解信息。

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

首先我们先配置好spring aop 环境
然后以一个类中的方法为切入点,通过反射机制获得目标方法参数信息

下面是我们要反射的类
Z,X都是事先自己写好的注解类

@Z(33)
public class DukePerformer {
    @Z(100)
    private  int q;
    private String name;
    public void setName(String name)
    {
        this.name=name;
    }
    public String getName()
    {
        return this.name;
    }
    @Z(77)
    public void perform(@Z int iiii,@X int ttt) {
        System.out.println(iiii);
        System.out.println(ttt);
    }
}

下面是我们在我们的aop切入函数,通过point参数getTarget()方法获取目标点所在类,然后通过反射去获取Annotation信息

public void takeSeat(ProceedingJoinPoint point)
    {      
        Annotation[][] annotations;
        Annotation annotation1 = null;
        Z z1 = point.getTarget().getClass().getAnnotation(Z.class);
        System.out.println("该类注解当前值:"+z1.value()+"\n\n\n\n");

        Method[] methods1 = point.getTarget().getClass().getDeclaredMethods();
        System.out.println("该类共有"+methods1.length+"个方法");
        for (Method method : methods1){
            annotation1 = method.getAnnotation(Z.class);
            if (annotation1!=null){
                System.out.println("方法"+method.getName()+"有Z注解:");
                z = (Z)annotation1;
                System.out.println("方法注解值:"+z1.value());

                annotations = method.getParameterAnnotations();
                System.out.println("该方法有"+annotations.length+"个方法有注解");
                for (Annotation[] annotation2 :annotations){
                    if (annotation2[0].annotationType() == X.class){
                        x = (X)annotation2[0];
                        System.out.println("注解类型"+x.annotationType().getName()+"的value值是:"+x.value());
                    }
                    if (annotation2[0].annotationType() == Z.class){
                        z = (Z)annotation2[0];
                        System.out.println("注解类型"+z.annotationType().getName()+"的value值是:"+z.value());
                    }
                }
            }else{
                System.out.println("方法"+method.getName()+"没有Z注解:");
            }

        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值