Why Customization required in ClassLoader
Many developers and system designers are not satisfied with the performance of default java classloaders work. To overcome such kind of condition many developers use own designed class loaders.
Custom class loaders are useful in complex application architectures consists of multiple modules/phases.
Various advantages of custom class loaders are.
1-Multiple unit(modular) architecture
Allows defining multiple class loader units which allowing to build simplex programming architecture.
2-Versioning
Supports multiple versions of the class within the same Virtual machine for different units/phases/modules.
3-Memory Management
Unwanted/Unused units can be removed which unloads the classes used by that unit, which cleans up memory.
4-Avoiding conflicts
Avoid conflicts at the time of multiple class loading and also defines the scope of the class to within the class loader.
5-Load classes from anywhere
It gives us the facility to load classes that can be loaded from anywhere. Example: database, networks, or local storage.
6-Runtime Reloading Modified Classes
It creates child class loader which allows loading modified classes at run time. Allows to the facility to add resources and classes dynamically.
Custom ClassLoader Example :
package com.navneet.javatutorial;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;public class CustomClassLoaderDemo extends ClassLoader{
@Override
public Class<> findClass(String name) {
byte[] byte1 = load(name);
return defineClass(name, byte1, 0, byte1.length);
}
private byte[] load(String loadedClassName) {
//Read Class Data
InputStream input = getClass().getClassLoader().getResourceAsStream(loadedClassName.replace(".", "/:")+".class");
ByteArrayOutputStream bAOS = new ByteArrayOutputStream();
int length =0;
try {
while((length=input.read())!=-1){
bAOS.write(length);
}
} catch (IOException ex) {
ex.printStackTrace();
}return bAOS.toByteArray();
}Step 2- Create Test class that have only one print method
package com.navneet.javatutorial;
public class Test {
public void print() {
System.out.println("Welcome to custom class loader example demo!");
}
}Step 3- Create RunCustomClassLoader which is used to load and run Test class
package com.navneet.javatutorial;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class RunCustomClassLoader {
public static void main(String[] args) {
try {
CustomClassLoaderDemo loader = new CustomClassLoaderDemo();// Load and find Test Class
Class<> c = loader.findClass("com.navneet.javatutorial.Test");
Object ob = c.newInstance();
Method md = c.getMethod("print");
md.invoke(ob);
System.out.println("Class loaded Successfully !!");
}catch (IllegalAccessException | NoSuchMethodException | InstantiationException | InvocationTargetException ex) {
}
}}
Program O/P:
Welcome to custom class loader example demo!
Class loaded Successfully !!