我需要通过使用注释作为切点来接受一些方法及其属性,但是如何访问这些方法属性.我有以下代码,成功地可以在方法运行之前运行代码,但是我不知道如何访问这些attrbiutes.
package my.package;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.pointcut;
@Aspect
public class MyAspect {
@pointcut(value="execution(public * *(..))")
public void anyPublicmethod() {
}
@Around("anyPublicmethod() && @annotation(myAnnotation )")
public Object myAspect(ProceedingJoinPoint pjp,MyAnnotation myAnnotation)
throws Throwable {
// how can I access method attributes here ?
System.out.println("hello aspect!");
return pjp.proceed();
}
}
解决方法
您可以从ProceedingJoinPoint对象获取它们:
@Around("anyPublicmethod() && @annotation(myAnnotation )")
public Object myAspect(final ProceedingJoinPoint pjp,final MyAnnotation myAnnotation) throws Throwable{
// retrieve the methods parameter types (static):
final Signature signature = pjp.getStaticPart().getSignature();
if(signature instanceof MethodSignature){
final MethodSignature ms = (MethodSignature) signature;
final Class<?>[] parameterTypes = ms.getParameterTypes();
for(final Class<?> pt : parameterTypes){
System.out.println("Parameter type:" + pt);
}
}
// retrieve the runtime method arguments (dynamic)
for(final Object argument : pjp.getArgs()){
System.out.println("Parameter value:" + argument);
}
return pjp.proceed();
}