简体   繁体   中英

Problems about Cglib proxy MethodInterceptor callback parameters

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM