目录导航
动态代理的简要说明
在java的动态代理机制中,有两个重要的类或接口,一个是 InvocationHandler(Interface)、另一个则是 Proxy(Class)。
一、 InvocationHandler(interface)的描述:
InvocationHandler is the interface implemented by the invocation handler of a proxy instance.
Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.
每一个动态代理类都必须要实现InvocationHandler这个接口,并且每个代理类的实例都关联到了一个handler,当我们通过代理对象调用 一个方法的时候,这个方法的调用就会被转发为由InvocationHandler这个接口的 invoke 方法来进行调用。我们来看看InvocationHandler这个接口的唯一一个方法 invoke 方法:
Object invoke(Object proxy, Method method, Object[] args) throws Throwable
这个方法接收三个参数和返回一个Object类型,它们分别代表的意思如下:
- proxy: 指代我们所代理的那个真实对象
- method: 指代的是我们所要调用真实对象的方法的Method对象
- args: 指代的是调用真实对象某个方法时接受的参数
返回的Object是指真实对象方法的返回类型,以上会在接下来的例子中加以深入理解。
the value to return from the method invocation on the proxy instance.
二、 Proxy(Class)的描述:
Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
Proxy这个类的作用就是用来动态创建一个代理对象。我们经常使用的是newProxyInstance这个方法:
public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException
参数的理解: