Custom ClassLoader

Dynamic Class Loading or Custom Class Loaders are few of the terms which is well known to a Java developer or who is touchbase with Java. now lets learn the term Class Loading and how does it work.

Class Loading is a term used in Java to load Java classes at the startup, Now we have have different instances wherein we have necessity of loading a class or you can say at below instances a class can be loaded to JVM,

  1. Bootstrap, It is responsible to load java.* packages, typically it is loading rt.jar(Also called runtime jar) and i18n.jar
  2. Extensions, JDK libraries are used to load by here, normally JRE’s EXT/LIB are loaded.
  3. System, Loads classes from system classpath or used to load custom classloaders.
Types of Class Loading?
Class Loading is a mechanism of loading classes at startup of application and is used widely to support runtime class loading, means if you want to change a class and don’t want to start your container again the class loading is best to implement it, now lets learn how many types of a class loading are there in Java,
Static Class Loading, If we are using “new” operator to create class object, this type of loading or creation of class object is called Static Class loading.

MySingleton ms = new MySingleton();

Dynamic Class Loading, Dynamic loading is a technique for programmatically invoking the functions of a
class loader at run time. Let us look at how to load classes dynamically. 

Class.forName(“com.tekhnologia.classloader.MySingleton”);

Now above code will load your class over JVM and now you can use this class anywhere in you class where you have define above line. Please follow below to create instance from above code,

Class mysingleClass = Class.forName(com.tekhnologia.classloader.MySingleton”);
MySingleton ms = ()mysingleClass.newInstance();
ms.runMethod();

Above code will load class MySingleton and by use of .newInsance() instance will be created then by instance method of class can be use.
Difference between Static and Dynamic Class Loading?
Static Class Loading, NoClassDefFoundException will be thrown when class not found.
Dynamic Class Loading, Will throw ClassNotFoundException.

Here we will learn how to create our own custom loader class so that we can load as we need the class,

package com.tekhnologia.classloader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
public class SingletonClassloader extends ClassLoader {
private Hashtable classes = new Hashtable();
public SingletonClassloader() {
super(SingletonClassloader.class.getClassLoader());
}
public Class loadClass(String className) throws ClassNotFoundException {
        return findClass(className);
    }
public Class findClass(String className){
        byte classByte[];
        Class result=null;
        result = (Class)classes.get(className);
        if(result != null){
            return result;
        }
     
        try{
            return findSystemClass(className);
        }catch(Exception e){
        }
        try{
        if(!classes.containsKey(className)){
           String classPath =    ((String)ClassLoader.getSystemResource(className.replace(‘.’,File.separatorChar)+”.class”).getFile()).substring(1);
           classByte = loadClassData(classPath);
            result = defineClass(className,classByte,0,classByte.length,null);
            classes.put(className,result);
            return result;
        }
        else
        return classes.get(className).getClass();
        }catch(Exception e){
            return null;
        }
    }
 
private byte[] loadClassData(String className) throws IOException{

        File f ;
        f = new File(className);
        int size = (int)f.length();
        byte buff[] = new byte[size];
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        dis.readFully(buff);
        dis.close();
        return buff;
    }
}

You can have this tested by below code
package com.tekhnologia.classloader;

public class SingletonCLtest {
public static void main(String[] args) {
SingletonClassloader scl = new SingletonClassloader();
String classpath =”com.tekhnologia.classloader.MySingleton”;
try {
scl.loadClass(classpath);
MySingleton.seeWhatHappen();
} catch (ClassNotFoundException e) {
System.out.println(“Class can not be loaded.”);
}
}
}

We frequently update my articles to best of my knowledge, please touch base with us to get maximum.
If you like reading Please share with others or provide feedback to make it better. 

Regards,
Bhanu Pratap