InvocationHandler的invoke方法的第一個參數問題

今天有同事問起,動態代理中的InvocationHandler的invoke方法的第一個參數。是代理類仍是委託類(即被代理類). 其實這個參數是代理類。咱們看一下生成的代理類就會明白:java

public interface ProxyInf {
   public void say();
}
public class TestProxy{
    public void say() {
       System.out.println("nothing");
    }
                      
    public static void main(String args[]) throws IOException{
         byte[] generateProxyClass = ProxyGenerator.generateProxyClass( 
                 "ProxyImpl", new Class<?>[] { ProxyInf.class}); 
         FileOutputStream fos = new FileOutputStream("c:\\ProxyImpl.class"); 
         fos.write(generateProxyClass); 
         fos.close(); 
    }
}

反編譯C盤下面的ProxyImpl.class類文件,你會發現:ide

public final class ProxyImpl extends Proxy
  implements ProxyInf
{
  private static Method m3;
  private static Method m1;
  private static Method m0;
  private static Method m2;
  public ProxyImpl(InvocationHandler paramInvocationHandler)
    throws {
    super(paramInvocationHandler);
  }
  public final void say()
    throws {
    try {
      this.h.invoke(this, m3, null);
      return;
    }
    catch (RuntimeException localRuntimeException) {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable){
    }
    throw new UndeclaredThrowableException(localThrowable);
  }
...
}

當你調用代理類的say方時,他調用的是InvokeHandler的invoke方法,並把自個作首參傳了進去。
就這樣吧.

this

相關文章
相關標籤/搜索