Custom ClassLoader Java Example
March 12, 2014
java.lang.ClassLoader loads a class. To load our own class we can create custom ClassLoader also. Using ClassLoader, we can load classes from desired location like from another location etc. A custom ClassLoader is a sub class of ClassLoader which will override some methods of ClassLoader. We will learn creating custom ClassLoader step by step.
Create a Custom ClassLoader class
To create a custom class loader, we will create a class that will extend ClassLoader. There is a method findClass() that must be overridden. Create a method that will load your given class from the class path. In our case we have created the method loadClassData() that will return byte[]. This byte array will be returned as Class by defineClass() method.CustomClassLoaderDemo.java
package com.concretepage.lang; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class CustomClassLoaderDemo extends ClassLoader { @Override public Class<?> findClass(String name) { byte[] bt = loadClassData(name); return defineClass(name, bt, 0, bt.length); } private byte[] loadClassData(String className) { //read class InputStream is = getClass().getClassLoader().getResourceAsStream(className.replace(".", "/")+".class"); ByteArrayOutputStream byteSt = new ByteArrayOutputStream(); //write into byte int len =0; try { while((len=is.read())!=-1){ byteSt.write(len); } } catch (IOException e) { e.printStackTrace(); } //convert into byte array return byteSt.toByteArray(); } }
Create a Test class
Now to load a class by our custom class loader, we will create a test class. Find the simple test class.Test.java
package com.concretepage.lang; public class Test { public void show(){ System.out.println("Hello World!"); } }
Create main class to test Custom ClassLoader
Now its time to test our custom class loader. Using reflection API, we will be able to read our test class with the help of our custom class loader as below.MainClass.java
package com.concretepage.lang; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class MainClass { public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { CustomClassLoaderDemo loader = new CustomClassLoaderDemo(); Class<?> c = loader.findClass("com.concretepage.lang.Test"); Object ob = c.newInstance(); Method md = c.getMethod("show"); md.invoke(ob); } }
Hello World!