Simple Java Custom Class Loader Implementation

Simple implementation of Java custom class loader. An example of the class usage is provided in the code snippet. Have in mind if you are using eclipse the application root folder during the implementation process is the project folder and not the bin folder. This may lead to ClassNotFoundException. This implementation can load classes from jar files which are in the class path!

/**
 * 
 * @author http://codeslices.net team
 * 
 */

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * Simple custom class loader implementation
 * 
 */
public class CustomClassLoader extends ClassLoader {

    /**
     * The HashMap where the classes will be cached
     */
    private Map<String, Class<?>> classes = new HashMap<String, Class<?>>();

    @Override
    public String toString() {
        return CustomClassLoader.class.getName();
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        if (classes.containsKey(name)) {
            return classes.get(name);
        }

        byte[] classData;

        try {
            classData = loadClassData(name);
        } catch (IOException e) {
            throw new ClassNotFoundException("Class [" + name
                    + "] could not be found", e);
        }

        Class<?> c = defineClass(name, classData, 0, classData.length);
        resolveClass(c);
        classes.put(name, c);

        return c;
    }

    /**
     * Load the class file into byte array
     * 
     * @param name
     *            The name of the class e.g. com.codeslices.test.TestClass}
     * @return The class file as byte array
     * @throws IOException
     */
    private byte[] loadClassData(String name) throws IOException {
        BufferedInputStream in = new BufferedInputStream(
                ClassLoader.getSystemResourceAsStream(name.replace(".", "/")
                        + ".class"));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int i;

        while ((i = in.read()) != -1) {
            out.write(i);
        }

        in.close();
        byte[] classData = out.toByteArray();
        out.close();

        return classData;
    }

    /**
     * Simple usage of the CustomClassLoader implementation
     * 
     * @param args
     * @throws ClassNotFoundException
     * @throws IllegalAccessException
     * @throws InstantiationException
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     */
    public static void main(String[] args) throws ClassNotFoundException,
            InstantiationException, IllegalAccessException,
            NoSuchMethodException, SecurityException, IllegalArgumentException,
            InvocationTargetException
    {
        CustomClassLoader loader = new CustomClassLoader();
        // This class should be in your application class path
        Class<?> c = loader.findClass("net.codeslices.test.TestClass");
        Object o = c.newInstance();
        Method m = c.getMethod("toString");
        System.out.println(m.invoke(o));
    }

}

Recommend this snippet

Post a new comment





You may use the following tags in the comment body: [br] for forcing new line, [code][/code] to enter programming code!

Enter the words you see *

Comments

Vishnu
2014-04-02 15:03:49
This example is good for standalone. In web application I am setting the classloader and all classes to null before running System.gc(). what should be the path of Java class in web application if the native method is called in a class that is called by JSP. Class ca = cl.findClass("com.codethesis.example.A");
Jennifer C.
2014-02-20 18:33:40
Very useful code snippet. I desperately needed an implementation of custom java classloader in order to handle dll unloading and this worked great!

Most Popular Snippets

Simple implementation of Java custom class loader. An example of the class usage is provided in the code snippet.

This snippet shows how to scale an image (jpeg, png, gif) to smaller or bigger size proportionally in php.

This snippet creates a custom URL class loader in Java. The class loader has to be fed with the names and locations of the classes before they could be used.

Strict email validation implementation in the php programming language.

Simple snippet showing how to make an entire div a clickable link with pure jQuery code.

This snippet creates a fixed width html 5 horizontal menu with the usage of pure css. No javascript is involved!

Latest Snippets

Strict email validation implementation in the php programming language.

Basic email validation implemented in the php programming language.

Example implementation of jQuery code which detects clicked external links and automatically opens them in a new window.

Powered by LeosPHP! All rights reserved!