在切入点内获取带注释的参数

2022-09-01 12:48:38

我有两个注释,如果我在方法周围有一个切点,我如何提取用注释的所述方法的参数?@LookAtThisMethod@LookAtThisParameter@LookAtThisMethod@LookAtThisParameter

例如:

@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?
    }

}

答案 1

我围绕另一个不同但类似的问题的答案来模拟我的解决方案。

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

我必须遍历目标类的原因是,被注释的类是接口的实现,因此返回 null。signature.getMethod().getParameterAnnotations()


答案 2
final String methodName = joinPoint.getSignature().getName();
    final MethodSignature methodSignature = (MethodSignature) joinPoint
            .getSignature();
    Method method = methodSignature.getMethod();
    GuiAudit annotation = null;
    if (method.getDeclaringClass().isInterface()) {
        method = joinPoint.getTarget().getClass()
                .getDeclaredMethod(methodName, method.getParameterTypes());
        annotation = method.getAnnotation(GuiAudit.class);
    }

此代码涵盖方法属于接口的情况


推荐