Dynamic Agent
The so-called dynamic is the generation of proxy classes during run time. Otherwise, there are 100 classes that need to be proxied, you have to manually write 100 proxy classes, and the code expands badly.
And my goal now is to figure out how the JDK implements dynamic proxies.
Read the source code of the proxy class to see the overall process:
1. We provide our own interfaces and class loaders, and then the JDK goes through class.forname to load and initialize these interfaces and generate type information.
2, with the type information of these interfaces, you can get all the information of the method by reflection
3. There are 2 options at this time: Generate the Java source code file for the proxy class from the existing information, and then dynamically compile the class file.
The JDK uses a different type of information that is written directly to the class file. Because the content distribution of the class file is fixed, it is possible to write a binary stream in the format of a class file.
The second type is more efficient than the first.
4. With the class file, you can call the DefineClass method to generate the type information for the proxy class
5, with the type information of the proxy class, it is possible to generate an instance of the proxy class by invoking the non-parametric construction method by reflection.
Through the dynamic proxy implementation principle, you can clearly see: the class loading mechanism is relatively flexible, as long as you can get the class file conforming to the specification, you can generate the corresponding type information, and then through reflection can do a lot of things.
However, the only regret for dynamic agents is that interfaces must be implemented, and there is another way to---cglib to implement dynamic proxies more flexibly. About Cglib, and listen to tell.
Class loading vs. Dynamic Proxy