Creating Custom Class Loader In JAVA

Posted By : Neeraj Kumar | 30-May-2018

In Java classes of any java program gets loaded into JVM from the java runtime via more than one class loaders. There is a delegation model of Java class loaders in which class loaders delegate class loading call to its immediate parent upto the top of the hierarchy which is the Bootstrap class loader. For the application classes to be loaded we specify CLASSPATH where the compiled .class files of all our classes resides. The Application class loaders loads  classes defined on this class path. Every java program has three basic class loaders

 

1. Bootstrap Class Loader

2. Extension Class Loader

3. Application Class Loader
 

All classes from java system runtime classes to extension classes to application classes gets loaded by these class loaders and can be loaded from other class loaders as well.

However, you can build your own custom class loader in java. Which will support these class loaders as parent in delegation class and if the class loading call failed for the parent the subsequent child which will be our custom class loader should be able to handle it.
 

Points to note here:

. This class loader will not load all classes.

. This will use java’s class loader delegation model.

. This will extend ClassLoader class

. This will load classes from the Database.

 

Main Class:

--------------------------------------------------------------------------------------------------------------------------------

package edu.nraj;

import edu.nraj.IQuote;

// run with -Djava.library.path=path-to-quth-DLL (e,g, C:\demos\LoadingFromDb\Client\lib\x64

public class Main {
   public static void main(String[] args) {
       try {
           SqlServerClassLoader cl = new SqlServerClassLoader("jdbc:sqlserver://localhost\\SQLExpress;databaseName=classloading;integratedSecurity=true");
           Class clazz = cl.findClass("edu.nraj.Quote");
           IQuote quote = (IQuote) clazz.newInstance();
           System.out.println(quote.getQuote());
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       } catch (InstantiationException e) {
           e.printStackTrace();
       } catch (IllegalAccessException e) {
           e.printStackTrace();
       }
   }
}

--------------------------------------------------------------------------------------------------------------------------------

 

SqlServerClassLoader Class:

 

--------------------------------------------------------------------------------------------------------------------------------

package edu.nraj;

import java.io.Writer;
import java.sql.*;

public class SqlServerClassLoader extends ClassLoader {
   private ClassLoader parent;
   private String connectionString;

   public SqlServerClassLoader(String connectionString) {
       this(ClassLoader.getSystemClassLoader(), connectionString);
   }

   public SqlServerClassLoader(ClassLoader parent, String connectionString) {
       super(parent);
       this.parent = parent;
       this.connectionString = connectionString;
   }

   @Override
   protected Class<?> findClass(String name) throws ClassNotFoundException {
       Class cls = null;
       try {
           cls = parent.loadClass(name);
       } catch (ClassNotFoundException cnfe) {
           byte[] bytes = new byte[0];
           try {
               bytes = loadClassFromDatabase(name);
           } catch (SQLException sqle) {
               throw new ClassNotFoundException("Unable to load class", sqle);
           }
           return defineClass(name, bytes, 0, bytes.length);
       }
       return cls;
   }

   private byte[] loadClassFromDatabase(String name) throws SQLException, ClassNotFoundException {
       PreparedStatement pstmt = null;
       Connection connection = null;
       byte[] data = null;
       try {
           connection = DriverManager.getConnection(connectionString);

           String sql = "select class from CLASSES where ClassName= ?";
           pstmt = connection.prepareStatement(sql);
           pstmt.setString(1, name);
           ResultSet rs = pstmt.executeQuery();

           if (rs.next()) {
               Blob blob = rs.getBlob(1);
               data = blob.getBytes(1, (int) blob.length());
               return data;
           }
       } catch (SQLException sqlex) {
           System.out.println("Unexpected exception: " + sqlex.toString());
       } catch (Exception ex) {
           System.out.println("Unexpected exception: " + ex.toString());
       } finally {
           if (pstmt != null) pstmt.close();
           if (connection != null) connection.close();
       }

       if(data == null){
           throw new ClassNotFoundException();
       }
       return data;
   }
}

 

--------------------------------------------------------------------------------------------------------------------------------

 

About Author

Author Image
Neeraj Kumar

Neeraj is a JAVA Developer who possesses skill set in: Data Structures, Core Java, Java Enterprise Edition (Servlets, JSP, Standard Java Beans), Spring (Spring-core, spring-MVC, spring-Data-Access, Spring-Data-JPA), Hibernate, JPA, HTML, CSS, JavaScri

Request for Proposal

Name is required

Comment is required

Sending message..