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.
Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with.
解释一下传入的三个参数:
proxy: the proxy instance that the method was invoked on (代理)
method: the Method instance corresponding to the interface method invoked on the proxy instance(java.lang.Method提供了关于某个方法的一系列信息)
args: an array of objects containing the values of the arguments passed in the method invocation on the proxy instance(某个参数需要传入的argument的数组 type 为 Object[])
final Class<?>[] intfs = interfaces.clone(); final SecurityManager sm = System.getSecurityManager(); if (sm != null) { checkProxyAccess(Reflection.getCallerClass(), loader, intfs); }
/* * Look up or generate the designated proxy class. */ Class<?> cl = getProxyClass0(loader, intfs);
/* * Invoke its constructor with the designated invocation handler. */ try { if (sm != null) { checkNewProxyPermission(Reflection.getCallerClass(), cl); }
final Constructor<?> cons = cl.getConstructor(constructorParams); final InvocationHandler ih = h; if (!Modifier.isPublic(cl.getModifiers())) { AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run(){ cons.setAccessible(true); returnnull; } }); } return cons.newInstance(new Object[]{h}); } catch (IllegalAccessException|InstantiationException e) { thrownew InternalError(e.toString(), e); } catch (InvocationTargetException e) { Throwable t = e.getCause(); if (t instanceof RuntimeException) { throw (RuntimeException) t; } else { thrownew InternalError(t.toString(), t); } } catch (NoSuchMethodException e) { thrownew InternalError(e.toString(), e); } }
1.我们首先利用getProxyClass0拿到了我们需要的代理class,type Class
1 2 3
//Look up or generate the designated proxy class.
Class<?> cl = getProxyClass0(loader, intfs);
2.接着我们通过代理class拿到了我们代理类的构造函数
1
final Constructor<?> cons = cl.getConstructor(constructorParams);
/** * Constructs a new {@code Proxy} instance from a subclass * (typically, a dynamic proxy class) with the specified value * for its invocation handler. * * @param h the invocation handler for this proxy instance * * @throws NullPointerException if the given invocation handler, {@code h}, * is {@code null}. */ protectedProxy(InvocationHandler h){ Objects.requireNonNull(h); this.h = h; }