Recently I came accross the java custom class loader api. I found one use over here, kamranzafar's blog I am a bit new to the class loader concept. Can any one explain in detail, what are the different scenarios where we may need it or we should use it?
Java uses ClassLoader implicitly when you use new , import keyword, the jvm will use the current class's classloader to load the dependent classes, so you can use the custom classloader to load a bootstrap class explicitly by using classloader.
Class loaders are responsible for loading Java classes dynamically to the JVM (Java Virtual Machine) during runtime. They're also part of the JRE (Java Runtime Environment). Therefore, the JVM doesn't need to know about the underlying files or file systems in order to run Java programs thanks to class loaders.
To create new custom class loaders, the process is similar in the Java SE 7 release as in previous releases. Create a subclass of ClassLoader , then override the findClass() method and possibly loadClass() .
We will create our own ClassLoader by extending the ClassLoader class and overriding the loadClass(String name) method. If the class name will start from com. journaldev then we will load it using our custom class loader or else we will invoke the parent ClassLoader loadClass() method to load the class.
Custom class loaders are useful in larger architectures consisting of several module/applications. Here are the advantages of the custom class loader:
The primary use is in Application servers so that they can run two applications and not have the classes conflict. i.e. if application 1 has a class with the same name as application 2, with a custom class loader application 1 will load its class and application 2 will load its class.
Also if a class is loaded by a custom class loader it is possible to unload that class from the JVM. Again useful in application servers.
Another use would be for instrumentation - One way of doing aspect oriented programming or when using some persistence API's. With a custom classloader you can add behaviour to the loaded classes before they are passed over to the running application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With