当前位置: 移动技术网 > IT编程>开发语言>Java > Java动态代理分析及简单实例

Java动态代理分析及简单实例

2019年07月22日  | 移动技术网IT编程  | 我要评论
  java动态代理 要想了解java动态代理,首先要了解什么叫做代理,熟悉设计模式的朋友一定知道在gof总结的23种设计模式中,有一种叫做代理(proxy)的

  java动态代理

要想了解java动态代理,首先要了解什么叫做代理,熟悉设计模式的朋友一定知道在gof总结的23种设计模式中,有一种叫做代理(proxy)的对象结构型模式,动态代理中的代理,指的就是这种设计模式。

在我看来所谓的代理模式,和23种设计模式中的“装饰模式”是一个东西。23种设计模式中将它们作为两种模式,网上也有些文章讲这两种模式的异同,从细节来看,确实可以人为地区分这两种模式,但是抽象到一定高度后,我认为这两种模式是完全一样的。因此学会了代理模式,也就同时掌握了装饰模式。

代理模式

代理模式简单来说,就是对一个对象进行包装,包装后生成的对象具有和原对象一样的方法列表,但是每个方法都可以是被包装过的。

静态代理

让我们先来看一段代码:

package common;

public class test {
  static interface subject{
    void sayhi();
    void sayhello();
  }
  
  static class subjectimpl implements subject{

    @override
    public void sayhi() {
      system.out.println("hi");
    }

    @override
    public void sayhello() {
      system.out.println("hello");
    }
  }
  
  static class subjectimplproxy implements subject{
    private subject target;
    
    public subjectimplproxy(subject target) {
      this.target=target;
    }
    
    @override
    public void sayhi() {
      system.out.print("say:");
      target.sayhi();
    }

    @override
    public void sayhello() {
      system.out.print("say:");
      target.sayhello();
    }
  }
  
  public static void main(string[] args) {
    subject subject=new subjectimpl();
    subject subjectproxy=new subjectimplproxy(subject);
    subjectproxy.sayhi();
    subjectproxy.sayhello();
  }
}

 这段代码中首先定义了一个subject接口,接口中有两个方法。

然后定义了subjectimpl类实现subject接口并实现其中的两个方法,到这里肯定是没问题的。

现在再定义一个subjuectimplproxy类,也实现subject接口。这个subjectimplproxy类的作用是包装subjectimpl类的实例,它的内部定义一个变量target来保存一个subjectimpl的实例。subjectimplproxy也实现了接口规定的两个方法,并且在它的实现版本中,都调用了subjectimpl的实现,但是又添加了自己的处理逻辑。

相信这段代码不难理解,它通过对subjectimpl进行包装,达到了给输出内容添加前缀的功能。这种代理方式叫做静态代理。

动态代理

从上面的演示中我们不难看出静态代理的缺点:我们对subjectimpl的两个方法,是进行的相同的包装,但是却要在subjectimplproxy里把相同的包装逻辑写两次,而且以后如果subject接口再添加新的方法,subjectimplproxy也必须要添加新的实现,尽管subjectimplproxy对所有方法的包装可能都是一样的。

下面我把上面例子的静态代理改成动态代理,我们来看一下区别:

package common;

import java.lang.invoke.methodhandle;
import java.lang.reflect.invocationhandler;
import java.lang.reflect.method;
import java.lang.reflect.proxy;

public class test {
  static interface subject{
    void sayhi();
    void sayhello();
  }
  
  static class subjectimpl implements subject{

    @override
    public void sayhi() {
      system.out.println("hi");
    }

    @override
    public void sayhello() {
      system.out.println("hello");
    }
  }
  
  static class proxyinvocationhandler implements invocationhandler{
    private subject target;
    public proxyinvocationhandler(subject target) {
      this.target=target;
    }

    @override
    public object invoke(object proxy, method method, object[] args) throws throwable {
      system.out.print("say:");
      return method.invoke(target, args);
    }
    
  }
  
  public static void main(string[] args) {
    subject subject=new subjectimpl();
    subject subjectproxy=(subject) proxy.newproxyinstance(subject.getclass().getclassloader(), subject.getclass().getinterfaces(), new proxyinvocationhandler(subject));
    subjectproxy.sayhi();
    subjectproxy.sayhello();
    
  }
}

 只看main方法的话,只有第二行和之前的静态代理不同,同样是生成一个subjectproxy代理对象,只是生成的代码不同了。静态代理是直接new 一个subjectimplproxy的实例,而动态代理则调用了java.lang.reflect.proxy.newproxyinstance()方法,我们来看一下这个方法的源码:

 public static object newproxyinstance(classloader loader,
                     class<?>[] interfaces,
                     invocationhandler h)
    throws illegalargumentexception
  {
    if (h == null) {
      throw new nullpointerexception();
    }

    /*
     * look up or generate the designated proxy class.
     */
    class<?> cl = getproxyclass(loader, interfaces);  //获取代理类的class

    /*
     * invoke its constructor with the designated invocation handler.
     */
    try {
      constructor cons = cl.getconstructor(constructorparams);  //constructorparams是写死的:{ invocationhandler.class },上边返回的代理类class一定是extends proxy的,而proxy有一个参数为invocationhandler的构造函数
      return cons.newinstance(new object[] { h });  //这里通过构造函数将我们自己定义的invocationhandler的子类传到代理类的实例里,当我们调用代理类的任何方法时,实际上都会调用我们定义的invocationhandler子类重写的invoke()函数
    } catch (nosuchmethodexception e) {
      throw new internalerror(e.tostring());
    } catch (illegalaccessexception e) {
      throw new internalerror(e.tostring());
    } catch (instantiationexception e) {
      throw new internalerror(e.tostring());
    } catch (invocationtargetexception e) {
      throw new internalerror(e.tostring());
    }
  }

上面的 class<?> cl = getproxyclass(loader, interfaces);  调用的getproxyclass方法:

public static class<?> getproxyclass(classloader loader,
                     class<?>... interfaces)
    throws illegalargumentexception
  {
    if (interfaces.length > 65535) {  //因为在class文件中,一个类保存的接口数量是用2个字节来表示的,因此java中一个类最多可以实现65535个接口
      throw new illegalargumentexception("interface limit exceeded");
    }

    class<?> proxyclass = null;

    /* collect interface names to use as key for proxy class cache */
    string[] interfacenames = new string[interfaces.length];

    // for detecting duplicates
    set<class<?>> interfaceset = new hashset<>();
     //验证interfaces里的接口是否能被类加载器加载,是否是接口,是否有重复的 
    for (int i = 0; i < interfaces.length; i++) {
      /*
       * verify that the class loader resolves the name of this
       * interface to the same class object.
       */
      string interfacename = interfaces[i].getname();
      class<?> interfaceclass = null;
      try {
        interfaceclass = class.forname(interfacename, false, loader);
      } catch (classnotfoundexception e) {
      }
      if (interfaceclass != interfaces[i]) {
        throw new illegalargumentexception(
          interfaces[i] + " is not visible from class loader");
      }

      /*
       * verify that the class object actually represents an
       * interface.
       */
      if (!interfaceclass.isinterface()) {
        throw new illegalargumentexception(
          interfaceclass.getname() + " is not an interface");
      }

      /*
       * verify that this interface is not a duplicate.
       */
      if (interfaceset.contains(interfaceclass)) {
        throw new illegalargumentexception(
          "repeated interface: " + interfaceclass.getname());
      }
      interfaceset.add(interfaceclass);

      interfacenames[i] = interfacename;
    }

    /*
     * using string representations of the proxy interfaces as
     * keys in the proxy class cache (instead of their class
     * objects) is sufficient because we require the proxy
     * interfaces to be resolvable by name through the supplied
     * class loader, and it has the advantage that using a string
     * representation of a class makes for an implicit weak
     * reference to the class.
     */
    list<string> key = arrays.aslist(interfacenames);  //使用interfaces列表作为key缓存在cache里,也就是实现了相同interfaces的代理类只会创建加载一次

    /*
     * find or create the proxy class cache for the class loader.
     */
    map<list<string>, object> cache;
    synchronized (loadertocache) {
      cache = loadertocache.get(loader);
      if (cache == null) {
        cache = new hashmap<>();
        loadertocache.put(loader, cache);
      }
      /*
       * this mapping will remain valid for the duration of this
       * method, without further synchronization, because the mapping
       * will only be removed if the class loader becomes unreachable.
       */
    }

    /*
     * look up the list of interfaces in the proxy class cache using
     * the key. this lookup will result in one of three possible
     * kinds of values:
     *   null, if there is currently no proxy class for the list of
     *     interfaces in the class loader,
     *   the pendinggenerationmarker object, if a proxy class for the
     *     list of interfaces is currently being generated,
     *   or a weak reference to a class object, if a proxy class for
     *     the list of interfaces has already been generated.
     */
     //看看缓存里有没有,如果有就直接取出来然后return,否则判断根据pendinggenerationmarker判断是否有其它线程正在生成当前的代理类,如果有则cache.wait()等待,如果没有则创建。

    synchronized (cache) {
      /*
       * note that we need not worry about reaping the cache for
       * entries with cleared weak references because if a proxy class
       * has been garbage collected, its class loader will have been
       * garbage collected as well, so the entire cache will be reaped
       * from the loadertocache map.
       */
      do {
        object value = cache.get(key);
        if (value instanceof reference) {
          proxyclass = (class<?>) ((reference) value).get();
        }
        if (proxyclass != null) {
          // proxy class already generated: return it
          return proxyclass;
        } else if (value == pendinggenerationmarker) {
          // proxy class being generated: wait for it
          try {
            cache.wait();
          } catch (interruptedexception e) {
            /*
             * the class generation that we are waiting for should
             * take a small, bounded time, so we can safely ignore
             * thread interrupts here.
             */
          }
          continue;
        } else {
          /*
           * no proxy class for this list of interfaces has been
           * generated or is being generated, so we will go and
           * generate it now. mark it as pending generation.
           */
          cache.put(key, pendinggenerationmarker);
          break;
        }
      } while (true);
    }
     //确认要生成的代理类所属的包,如果interfaces里所有接口都是public的,代理类所属包就是默认包;如果有interface不是public,那么所有不是public的interface必须在一个包里否则报错。
    try {
      string proxypkg = null;   // package to define proxy class in

      /*
       * record the package of a non-public proxy interface so that the
       * proxy class will be defined in the same package. verify that
       * all non-public proxy interfaces are in the same package.
       */
      for (int i = 0; i < interfaces.length; i++) {
        int flags = interfaces[i].getmodifiers();
        if (!modifier.ispublic(flags)) {
          string name = interfaces[i].getname();
          int n = name.lastindexof('.');
          string pkg = ((n == -1) ? "" : name.substring(0, n + 1));
          if (proxypkg == null) {
            proxypkg = pkg;
          } else if (!pkg.equals(proxypkg)) {
            throw new illegalargumentexception(
              "non-public interfaces from different packages");
          }
        }
      }

      if (proxypkg == null) {   // if no non-public proxy interfaces,
        proxypkg = "";     // use the unnamed package
      }

      {
        /*
         * choose a name for the proxy class to generate.
         */
        long num;
        synchronized (nextuniquenumberlock) {
          num = nextuniquenumber++;
        }
        string proxyname = proxypkg + proxyclassnameprefix + num;  //生成代理类的名字,proxypkg是上面确定下来的代理类所在的包名,proxyclassnameprefix是写死的字符串“$proxy”,num是一个全局唯一的long型数字,从0开始累积,每次生成新的代理类就+1,从这里也能看出生成的动态代理类的数量不能超过long.maxvalue
        /*
         * verify that the class loader hasn't already
         * defined a class with the chosen name.
         */

        /*
         * generate the specified proxy class.
         */
        byte[] proxyclassfile = proxygenerator.generateproxyclass(
          proxyname, interfaces);  //生成一个以proxyname为类名的,实现了interfaces里所有接口的类的字节码
        try {
          proxyclass = defineclass0(loader, proxyname,
            proxyclassfile, 0, proxyclassfile.length);  //加载生成的类
        } catch (classformaterror e) {
          /*
           * a classformaterror here means that (barring bugs in the
           * proxy class generation code) there was some other
           * invalid aspect of the arguments supplied to the proxy
           * class creation (such as virtual machine limitations
           * exceeded).
           */
          throw new illegalargumentexception(e.tostring());
        }
      }
      // add to set of all generated proxy classes, for isproxyclass
      proxyclasses.put(proxyclass, null);

    } finally {
      /*
       * we must clean up the "pending generation" state of the proxy
       * class cache entry somehow. if a proxy class was successfully
       * generated, store it in the cache (with a weak reference);
       * otherwise, remove the reserved entry. in all cases, notify
       * all waiters on reserved entries in this cache.
       */
       //创建成功,则将cache中该key的pendinggenerationmarker替换为实际的代理类的弱引用,否则也要清除pendinggenerationmarker标记;不管是否成功,都要执行cache.notifyall(),让其它要创建相同代理类并且执行了cache.wait()的线程恢复执行。
      synchronized (cache) {
        if (proxyclass != null) {
          cache.put(key, new weakreference<class<?>>(proxyclass));
        } else {
          cache.remove(key);
        }
        cache.notifyall();
      }
    }
    return proxyclass; //最后返回代理类class
  }

到这里,我们已经把动态代理的java源代码都解析完了,现在思路就很清晰了:

proxy.newproxyinstance(classloader loader,class<?>[] interfaces,invocationhandler h) 方法简单来说执行了以下操作:

1.生成一个实现了参数interfaces里所有接口且继承了proxy的代理类的字节码,然后用参数里的classloader加载这个代理类。

2.使用代理类父类的构造函数 proxy(invocationhandler h)来创造一个代理类的实例,将我们自定义的invocationhandler的子类传入。

3.返回这个代理类实例,因为我们构造的代理类实现了interfaces(也就是我们程序中传入的subject.getclass().getinterfaces())里的所有接口,因此返回的代理类可以强转成subject类型来调用接口中定义的方法。

现在我们知道了用proxy.newproxyinstance()返回的subjectproxy可以成功强转成subject类型来调用接口中定义的方法了,那么在调用方法后,代理类实例怎么进行处理的呢,这就需要看一下代理类的源码了。但是代理类是程序动态生成字节码加载的,怎么看源码呢?没关系,可以在main方法中加入system.getproperties().put("sun.misc.proxygenerator.savegeneratedfiles","true"),这样就会把生成的代理类class文件保存在本地磁盘上,然后再反编译可以得到代理类的源码:

package common;

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 test.subject
{
 private static method m4;
 private static method m1;
 private static method m3;
 private static method m0;
 private static method m2;
 
 static
 {
   try {
     m4 = class.forname("test$subject").getmethod("sayhello", new class[0]);
     m1 = class.forname("java.lang.object").getmethod("equals", new class[] { class.forname("java.lang.object") });
     m3 = class.forname("test$subject").getmethod("sayhi", new class[0]);
     m0 = class.forname("java.lang.object").getmethod("hashcode", new class[0]);
     m2 = class.forname("java.lang.object").getmethod("tostring", new class[0]);
  } catch (exception e) {
    throw new runtimeexception(e);
  }
 }

 public $proxy0(invocationhandler paraminvocationhandler)
 {
  super(paraminvocationhandler);
 }

 public final void sayhello()
 {
  try
  {
   this.h.invoke(this, m4, null);
   return;
  }
  catch (runtimeexception localruntimeexception)
  {
   throw localruntimeexception;
  }
  catch (throwable localthrowable)
  {
    throw new undeclaredthrowableexception(localthrowable);
  }
 }

 public final boolean equals(object paramobject)
 {
  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 sayhi()
 {
  try
  {
   this.h.invoke(this, m3, null);
   return;
  }
  catch (runtimeexception localruntimeexception)
  {
   throw localruntimeexception;
  }
  catch (throwable localthrowable)
  {
    throw new undeclaredthrowableexception(localthrowable);
  }
 }

 public final int hashcode()
 {
  try
  {
   return ((integer)this.h.invoke(this, m0, null)).intvalue();
  }
  catch (runtimeexception localruntimeexception)
  {
   throw localruntimeexception;
  }
  catch (throwable localthrowable)
  {
    throw new undeclaredthrowableexception(localthrowable);
  }
 }

 public final string tostring()
 {
  try
  {
   return (string)this.h.invoke(this, m2, null);
  }
  catch (runtimeexception localruntimeexception)
  {
   throw localruntimeexception;
  }
  catch (throwable localthrowable)
  {
    throw new undeclaredthrowableexception(localthrowable);
  }
 }
}

我们可以看到代理类内部实现比较简单,在调用每个代理类每个方法的时候,都用反射去调h的invoke方法(也就是我们自定义的invocationhandler的子类中重写的invoke方法),用参数传递了代理类实例、接口方法、调用参数列表,这样我们在重写的invoke方法中就可以实现对所有方法的统一包装了。

总结:

动态代理相对于静态代理在使用上的优点主要是能够对一个对象的所有方法进行统一包装,而且后期被代理的类添加方法的时候动态代理类不需要改动。

缺点是要求被代理的类必须实现了接口,因为动态代理类在实现的时候继承了proxy类,java不支持多继承,因此动态代理类只能根据接口来定义方法。

最后动态代理之所以叫做动态代理是因为java在实现动态代理的时候,动态代理类是在运行时动态生成和加载的,相对的,静态代理类和其他普通类一下,在类加载阶段就加载了。

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网