今天有同事问起,动态代理中的InvocationHandler的invoke方法的第一个参数。是代理类还是委托类(即被代理类). 其实这个参数是代理类。我们看一下生成的代理类就会明白:
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类文件,你会发现:
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方法,并把自个做首参传了进去。
就这样吧.