您的位置:首页 > 编程语言 > Java开发

java动态代理机制

2016-03-07 23:09 477 查看
需要用到的类和接口:

类:Proxy

接口:InvocationHandler

InvocationHandler:

接口方法:

Object invoke(Object proxy, Method method, Object[] args) throws Throwable


方法参数:

Object proxy:代理调用方法的实例
Method method:执行的方法
Object[] args:执行方法时的参数对象数组


返回值:返回代理对象执行方法后的结果

作用:

每一个动态代理类都必须要实现InvocationHandler这个接口

每个代理类的实例都关联到了一个handler

当我们通过代理对象调用一个方法的时候,这个方法的调用就会被转发为由InvocationHandler这个接口的 invoke 方法来进行调用

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:

用到的方法:

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces,  InvocationHandler h)  throws IllegalArgumentException


方法参数:

ClassLoader loader:ClassLoader对象,用于对生成的代理对象进行加载
Class<?>[] interfaces:Interface对象的数组,代理对象实现的方法
InvocationHandler h:InvocationHandler对象,用指定的加载器加载,并且实现了指定的接口的InvocationHandler的代理实例 


作用:得到一个动态的代理对象

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: