如何获得Java动态代理的代理类
JDK 代理生成器,在生成类是会根据参数“sun.misc.ProxyGenerator.saveGeneratedFiles”来决定是否将二进制保存到本地文件中, 具体的路径查看源码: ProxyGenerator.access$000(this.val$name) + ".class" 根据access$000这个方法生成的路径来保存
在openjdk中这个access$000 是对应
private static String dotToSlash(String name) { return name.replace('.', '/'); }
所以文件是保存在
FileOutputStream localFileOutputStream = new FileOutputStream(ProxyGenerator.access$000(this.val$name) + ".class");
可以测试一下这个文件存放的具体路径:
FileOutputStream file = new FileOutputStream("$Proxy0" + ".class");
System.out.println(new File("$Proxy0" + ".class").getAbsolutePath());
这样在下面生成动态代理类的时候会将class文件保存
反编译class文件,可以看到有一个参数为InvocationHandler的构造方法,实现接口方法种的代码如下:
public final void printA()
throws
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}
表明代理类只是做了一层封装,具体实现是在InvocationHandler中来做。
我还是没找到文件位置,加入 FileOutputStream file = new FileOutputStream("$Proxy0" + ".class");
System.out.println(new File("$Proxy0" + ".class").getAbsolutePath()); 着两行生成的类文件是空的,没有啊
很有用,很实用
很好的文章!