java动态代理机制

需要用到的类和接口:

  1. 类:Proxy
  2. 接口:InvocationHandler

InvocationHandler:

  1. 接口方法:
    Object invoke(Object proxy, Method method, Object[] args) throws Throwable
  2. 方法参数:
    Object proxy:代理调用方法的实例
    Method method:执行的方法
    Object[] args:执行方法时的参数对象数组
  3. 返回值:返回代理对象执行方法后的结果
  4. 作用:
    • 每一个动态代理类都必须要实现InvocationHandler这个接口
    • 每个代理类的实例都关联到了一个handler
    • 当我们通过代理对象调用一个方法的时候,这个方法的调用就会被转发为由InvocationHandler这个接口的 invoke 方法来进行调用
  5. JDK注释(部分截取):
    @param   proxy the proxy instance that the method was invoked on
    @param   method the {@code Method} instance corresponding to the interface method invoked on the proxy instance. 
    @param   args an array of objects containing the values of the arguments passed in the method invocation on the proxy instance, or {@code null}          if interface method takes no arguments.
    @return  the value to return from the method invocation on the proxy instance.  

Proxy:

  1. 用到的方法:
    public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,  InvocationHandler h)  throws IllegalArgumentException
  2. 方法参数:
    ClassLoader loader:ClassLoader对象,用于对生成的代理对象进行加载
    Class<?>[] interfaces:Interface对象的数组,代理对象实现的方法
    InvocationHandler h:InvocationHandler对象,用指定的加载器加载,并且实现了指定的接口的InvocationHandler的代理实例 
  3. 作用:得到一个动态的代理对象
  4. JDK注释:
    @param   loader the class loader to define the proxy class
    @param   interfaces the list of interfaces for the proxy class to implement
    @param   h the invocation handler to dispatch method invocations to
    @return  a proxy instance with the specified invocation handler of a proxy class that is defined by the specified class loader and that 
    implements the specified interfaces

     

posted @ 2016-03-07 23:09  账号早已注销  阅读(374)  评论(0编辑  收藏  举报