JAVA language: how to customize the class loader?

The focus of this article

In the previous course, we have learned the parental delegation mechanism. If we want to customize a class loader, then we only need to inherit ClassLoader and define our own findClass, which is how our own class loader works. It works, and loadClass is the parental delegation mechanism. We can use ClassLoader directly, so that the parental delegation mechanism is not destroyed.

custom class loader

Because the Shiy class is not placed in the current directory, when calling loadClass(packageNamePath), only the name of the class is passed, and the App loader cannot load it, so at this time it will go through the parent delegation mechanism and finally fall to our custom In the hands of the class loader, and our custom class loader knows the absolute path, so it can definitely be found and loaded, that is, the findClass method is called. Let's take a look at its logic:

As shown above, it reads the class file and converts it into a binary byte array, and then calls the defineClass method to convert the byte array into a class object, and the loading work is completed at this time.

important point

It is necessary to ensure that there is a Shi.class object under the D disk. Generally, we program in the compilation tool, so we only need to find the class file corresponding to the java class in the compilation tool, and then we can load it. code show as below:

As shown above, we program in idea, and then create a Hello class in com.huanfeng.bean, and then idea will automatically be in the C:\Users\feng\IdeaProjects\spring2\target\classes\com\huanfeng\bean path Then we only need to give the class path, then the class autoloader can help us complete the class loading work.

Guess you like

Origin blog.csdn.net/huanfeng_AI/article/details/132114033