在切入点中获取带注释的参数
问题内容:
我有两个注释,@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?
}
}
问题答案:
我围绕着另一个不同但相似的问题的其他答案对解决方案进行了建模。
MethodSignature signature = (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。