Java -- JDK dynamic proxy core source code parsing, java -- jdk source code
1. First, let's take a look at how to use JDK dynamic Proxy:
Public static void main (String [] args) {/*** creates a Bean object that implements the BeanInterFace interface */BeanInterFace bean = new Bean (); /*** create a MyProxy object that implements the InvocationHandler interface and injects the bean into MyProxy */InvocationHandler invocationHandler = new MyProxy (bean ); /*** call the JDK Proxy class and use the newProxyInstance method to directly generate the Proxy object of the Bean object * Note: Classloader must use the ClassLoader of the actual Proxy object, otherwise, the problem of repeated calls */BeanInterFace beanProxy = (BeanInterFace) Proxy. newProxyInstance (bean. getClass (). getClassLoader (), bean. getClass (). getInterfaces (), invocationHandler);/*** use proxy object */System. out. println (beanProxy. getClass (). getName (); beanProxy. say ();}
2. Let's take a look at how the JDK source code implements dynamic proxy.
Proxy. newProxyInstance will eventually call Proxy. ProxyClassFactory. apply () to generate Proxy Class
// Create a proxyname by using package + ClassName + id
String proxyName = proxyPkg + proxyClassNamePrefix + num;/** the proxy Class is generated here, And the binary byte [] array */byte [] proxyClassFile = ProxyGenerator is returned for compilation. generateProxyClass (proxyName, interfaces, accessFlags); try {
// The ProxyClass is loaded here. The system appClassLoader is used for loading. So far, I have not understood how to use it. The native method return defineClass0 (loader, proxyName, proxyClassFile, 0, proxyClassFile. length);} catch (ClassFormatError e) {/** A ClassFormatError here means that (barring bugs in the * proxy class generation code) there was some other * invalid aspect of the arguments supplied to the proxy * class creation (such as virtual machine limitations * exceeded ). */throw new IllegalArgumentException (e. toString ());}
3. How is a specific proxyClass generated?
Generally:
ProxyClass has a constructor. The constructor parameter is the InvocationHandler interface. After proxyClass is instantiated, the reference of InvocationHandler is stored in its own attributes, then, each method of proxyClass triggers the InvocationHandler's invoke method and calls the method of the real object through reflection.