需要用到的类和接口:
- 类: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