欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdk动态代理的实现原理

程序员文章站 2024-03-14 20:20:35
...

jdk动态代理实际上是jvm帮我们建成的类实现我们传入的接口,加载字节码到jvm。实际上就是帮我们拼接的字符串和我们传进去的接口进行拼接,然后生成字节码加载进虚拟机。代理类持有InvocationHandler的引用,当我们调用方法时实际上调用的是InvocationHandler的引用的invoke方法,invoke方法中再进行反射调用方法。jdk动态代理只能代理接口

接口类:

public interface Person {
public void eat();
}

实现类:

public class Man implements Person{

    @Override
    public void eat() {
        System.out.print("我吃饭了");

    }

}

InvocationHandler的实现类:

public class MyHandler implements InvocationHandler{
    private Object object;
    public MyHandler(Object object) {

        this.object=object;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // TODO Auto-generated method stub
                doBefore();
                Object result;
                result=method.invoke(this.object, args);//这里是不是很熟悉,可以看看反射
                doAfter();
                return result;
            }
        private void doBefore(){
            System.out.println("方法执行前");
        }
        private void doAfter(){
            System.out.println("方法执行后");
        }
        }

测试类:

public class Test {
public static void main(String[] args) {
    System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
    Person man=new Man();
    MyHandler handler=new MyHandler(man);
    Person proxy=(Person) Proxy.newProxyInstance(man.getClass().getClassLoader(), man.getClass().getInterfaces(), handler);
    System.out.println(proxy.getClass());
    proxy.eat();
}
}

System.getProperties().put(“sun.misc.ProxyGenerator.saveGeneratedFiles”,”true”);会保存生成的动态代理类$Proxy0,生成的代理类会自动新建文件夹存放在com/sun/proxy下

jdk动态代理的实现原理

反编译后如下:

package com.sun.proxy;

import com.gjh.test.Person;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy
  implements Person
{
  private static Method m1;
  private static Method m3;
  private static Method m2;
  private static Method m0;

  public $Proxy0(InvocationHandler paramInvocationHandler)
    throws 
  {
    super(paramInvocationHandler);
  }

  public final boolean equals(Object paramObject)
    throws 
  {
    try
    {
      return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final void eat()
    throws 
  {
    try
    {
      this.h.invoke(this, m3, null);
      return;
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final String toString()
    throws 
  {
    try
    {
      return (String)this.h.invoke(this, m2, null);
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  public final int hashCode()
    throws 
  {
    try
    {
      return ((Integer)this.h.invoke(this, m0, null)).intValue();
    }
    catch (RuntimeException localRuntimeException)
    {
      throw localRuntimeException;
    }
    catch (Throwable localThrowable)
    {
    }
    throw new UndeclaredThrowableException(localThrowable);
  }

  static
  {
    try
    {
      m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
      m3 = Class.forName("com.gjh.test.Person").getMethod("eat", new Class[0]);
      m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
      m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
      return;
    }
    catch (NoSuchMethodException localNoSuchMethodException)
    {
      throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
    }
    catch (ClassNotFoundException localClassNotFoundException)
    {
    }
    throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
  }
}