Reputation: 161
When using Spring Cglib proxy, we need to implement a MethodInterceptor callback, I have some problems about this callback. To make it clearer, let's use a simple example.
Here is my target class MyPlay.java
public class MyPlay {
public void play() {
System.out.println("MyPlay test...");
}
}
And I created a callback:
public class CglibMethodInterceptor implements MethodInterceptor {
private Object target;
public CglibMethodInterceptor(Object target) {
this.target = target;
}
public Object getProxy() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(target.getClass());
enhancer.setCallback(this);
return enhancer.create();
}
@Override
public Object intercept(
Object o,
Method method,
Object[] objects,
MethodProxy methodProxy) throws Throwable {
System.out.println("CGLIB prep work...");
Object obj = method.invoke(target, objects);
System.out.println("CGLIB post work...");
return obj;
}
}
In my Main class:
MyPlay myPlay = new MyPlay();
cglibMethodInterceptor = new CglibMethodInterceptor(myPlay);
Play myPlayProxy = (Play) cglibMethodInterceptor.getProxy();
myPlay.play();
myPlayProxy.play();
I'm confused about the meaning of the parameters of the intercept method:
@Override
public Object intercept(
Object o,
Method method,
Object[] objects,
MethodProxy methodProxy) throws Throwable {
}
So, I set up a breakpoint to at the myPlayProxy.play() and step into it. I took a screenshot:
Problem: What are the method
and methodProxy
parameters? What is the difference between them? When I use the methodProxy to invoke, it also works, which confuses me.
Object obj = method.invoke(target, objects);
// This also works, why?
// Object obj = methodProxy.invoke(target, objects);
Upvotes: 0
Views: 774
Reputation: 11474
The Javadoc says:
The original method may either be invoked by normal reflection using the Method object, or by using the MethodProxy (faster).
I don't know what makes it faster.
Upvotes: 1