JDK提供了Proxy类,这个类属于工具类,通过Proxy.newProxyInstance(要生成代理对象的类所在的classLoader, 要生成代理对象的类的接口, InvocationHandler的实例);
这个类生成出来的代理对象如下:
$Proxy0 extend Proxy implements IMyService{
private static Method m1;
private static Method m2;
public $Proxy0(InvocationHandler h) {
super(h);
}
public final void myMethod001(){
try {
h.invoke(this,m1,null);
}
catch (Error _ex){}
catch(Throwable throwable){
throw new UndeclaredThrowableException(throwable);
}
}
}
其他方法,比如:hashCode,ToString,equal就不写出来了,其实还是里面的实现机制就是委托
如何得到自己代理对象的class文件内容呢?
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces);
File f = new File("class/test.class");
FileOutputStream fos = new FileOutputStream(f);
fos.write(proxyClassFile);
fos.flush();
fos.close();
通过反编译工具查看test.class文件就可以了