Get annotated parameters inside a pointcut

25,372

Solution 1

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.

Solution 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);
    }

This code covers the case where the Method belongs to the interface

Share:
25,372
Bobby
Author by

Bobby

I work hard, learn fast, work on cars, read blogs, play video games, read books, watch football, study code, write code. That's me, Robert Peck, I'm an Eagle Scout and a programmer. StackOverflow Careers: http://careers.stackoverflow.com/peck Website: https://soldiermoth.com Twitter: http://twitter.com/soldiermoth Google Plus: https://profiles.google.com/u/0/soldier.moth Github Profile: http://github.com/soldiermoth

Updated on December 05, 2020

Comments

  • Bobby
    Bobby over 3 years

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