四、方法调用
在JdkDynamicAopProxy类的invoke()方法中创建了一个ReflectiveMethodInvocation类,该方法将执行拦截器链和最终的方法调用:
public class ReflectiveMethodInvocation implements ProxyMethodInvocation, Cloneable {
public Object proceed() throws Throwable {
// 若拦截器执行完毕,则运行目标对象上的方法
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size()) {
return invokeJoinpoint();
}
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
...
// 计算动态interceptor是否执行
}
else {
// 调用拦截器
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(nextInvocation());
}
}
private ReflectiveMethodInvocation nextInvocation() throws CloneNotSupportedException {
ReflectiveMethodInvocation invocation = (ReflectiveMethodInvocation) clone();
invocation.currentInterceptorIndex = this.currentInterceptorIndex + 1;
invocation.parent = this;
return invocation;
}
...
}
invokeJoinpoint()方法将最终调用被代理的方法:
protected Object invokeJoinpoint() throws Throwable {
return AopUtils.invokeJoinpointUsingReflection(this.target, this.method, this.arguments);
}