在切入点内获取带注释的参数 [英] Get annotated parameters inside a pointcut

查看:28
本文介绍了在切入点内获取带注释的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个注释 @LookAtThisMethod@LookAtThisParameter,如果我有一个关于 @LookAtThisMethod 的方法的切入点,我如何提取使用@LookAtThisParameter注解的所述方法的参数?

例如:

@Aspect公共类 LookAdvisor {@Pointcut("@annotation(lookAtThisMethod)")public void lookAtThisMethodPointcut(LookAtThisMethod lookAtThisMethod){}@Around("lookAtThisMethodPointcut(lookAtThisMethod)")public void lookAtThisMethod(ProceedingJoinPoint joinPoint, LookAtThisMethod lookAtThisMethod) 抛出 Throwable {for(对象参数:joinPoint.getArgs()){//我可以在这里获取参数值}//我可以通过以下方式获取方法签名:joinPoint.getSignature.toString();//如何获取哪些参数用@LookAtThisParameter 进行了注释?}}

解决方案

我围绕这个其他答案 另一个不同但相似的问题.

MethodSignature 签名 = (MethodSignature) joinPoint.getSignature();String methodName = signature.getMethod().getName();Class[] parameterTypes = signature.getMethod().getParameterTypes();Annotation[][] annotations = joinPoint.getTarget().getClass().getMethod(methodName,parameterTypes).getParameterAnnotations();

我必须通过目标类的原因是因为被注释的类是一个接口的实现,因此signature.getMethod().getParameterAnnotations()返回null.>

I have two annotation @LookAtThisMethod and @LookAtThisParameter, if I have a pointcut around the methods with @LookAtThisMethod how could I extract the parameters of said method which are annotated with @LookAtThisParameter?

For example:

@Aspect
public class LookAdvisor {

    @Pointcut("@annotation(lookAtThisMethod)")
    public void lookAtThisMethodPointcut(LookAtThisMethod lookAtThisMethod){}

    @Around("lookAtThisMethodPointcut(lookAtThisMethod)")
    public void lookAtThisMethod(ProceedingJoinPoint joinPoint, LookAtThisMethod lookAtThisMethod) throws Throwable {
        for(Object argument : joinPoint.getArgs()) {
            //I can get the parameter values here
        }

        //I can get the method signature with:
        joinPoint.getSignature.toString();


        //How do I get which parameters  are annotated with @LookAtThisParameter?
    }

}

解决方案

I modeled my solution around this other answer to a different but similar question.

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getMethod().getName();
Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
Annotation[][] annotations = joinPoint.getTarget().getClass().getMethod(methodName,parameterTypes).getParameterAnnotations();

The reason that I had to go through the target class was because the class that was annotated was an implementation of an interface and thusly signature.getMethod().getParameterAnnotations() returned null.

这篇关于在切入点内获取带注释的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆