ITeye博客

如何获得Java动态代理的代理类

samttsch · 2011-09-18 23:46 · 学习 · 编程语言 · Markdown

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中来做。

评论(3)

  1. #3 楼 · heshuanxu · 2016-09-21 13:50

    我还是没找到文件位置,加入 FileOutputStream file = new FileOutputStream("$Proxy0" + ".class");

    System.out.println(new File("$Proxy0" + ".class").getAbsolutePath()); 着两行生成的类文件是空的,没有啊

  2. #2 楼 · abc08010051 · 2013-10-14 21:09

    很有用,很实用

  3. #1 楼 · daly1987 · 2011-12-18 21:54

    很好的文章!

评论功能维护中,当前仅展示历史评论。