Class loading vs. Dynamic Proxy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.