When you want to load class into the Java Virtual Machine(JVM), Custom Class Loader is used.
Why Custom Class Loader?
When your class has some specific needs as follows..
- Isolate modules
- Plugins
- Control class
- Non- standard sources(Databases, Encrypted Files)
Types of Class Loaders:
There are 4 types of class loaders. Here is the list.
- Bootstrap:
This Class Loader loads the core
Java classes. It uses Internal JVM resources.
- Platform:
This type uses the platform-specific
classes and modules. It Loads Java module system.
- System:
This class loader deals with
application’s classes. It includes the class path.
- Custom:
When you want to load user
defined classes like plugin, this concept is used.
Let us create an example….
First, the built – in package is included.
Next, the function findClass() is overridden.
public class MyClassLoaderEg extends ClassLoader {
@Override
protected
Class<?> findClass(String c_name) throws ClassNotFoundException {
byte[] cData =
loadClassData(c_name);
return
defineClass(c_name, cData, 0, cData.length);
}
private byte[]
loadClassData(String className) {
// it loads
the byte from file
}
}
You typically extend java.lang.ClassLoader and override the findClass(String
name) method:
public class MyClassLoader extends ClassLoader {
@Override
protected
Class<?> findClass(String name) throws ClassNotFoundException {
byte[]
classData = loadClassData(name); // Your logic to read class bytes
return
defineClass(name, classData, 0, classData.length);
}
private byte[] loadClassData(String className) {
// Load class
bytes from file, network, etc.
}
}
In the main function, include the below code.
MyClassLoader ld = new MyClassLoader();
Class<?> cl = ld.loadClass(“sample.MyClass”);
Object in = cl.getDeclaredConstructor().newInstance();
That's all. A sample Custom class loader coding is included. Hope, this blog post is useful to you. Keep Coding!!!