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

sol*_*oth 24 java aop annotations aspectj

我有两个注解@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?
    }

}
Run Code Online (Sandbox Code Playgroud)

sol*_*oth 45

我模仿我的解决方案围绕另一个不同但相似的问题的答案.

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

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

  • 非常感谢.在找到这个答案之前我浪费了很多时间. (2认同)
  • 对我来说`signature.getMethod().getParameterAnnotations()` 返回接口的方法而不是实现。因此,如果注释仅在实现上,则此调用将为空。 (2认同)
  • `signature.getMethod().getAnnotation()`也可以.记住注释应该有`@Retention(RetentionPolicy.RUNTIME)`. (2认同)

小智 5

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);
    }
Run Code Online (Sandbox Code Playgroud)

这段代码涵盖了Method属于接口的情况