custom classloader code example
Example 1: custom classloader
package test.frugalis;
public class Frugalis {
public void printMyName(){
System.out.println("Welcome Frugalis Minds");
}
}
Example 2: custom classloader
loader name---- sun.misc.Launcher$AppClassLoader
Class Loading Started for test.frugalis.Frugalis
*********Inside getClass*********
Name of Filetest\frugalis\Frugalis.class
<<<<<<<<<Inside loadClassData>>>>>>
Size of byte array 519
Class Loading Started for java.lang.Object
Loaded class name: test.frugalis.Frugalis
Class Loading Started for java.lang.System
Class Loading Started for java.io.PrintStream
Welcome Frugalis Minds
Example 3: custom classloader
package test.main;
import java.lang.reflect.InvocationTargetException;
public class Test {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, Exception {
MyClassLoader loader = new MyClassLoader(
Test.class.getClassLoader());
System.out.println("loader name---- " +loader.getParent().getClass().getName());
Class<?> clazz =
loader.loadClass("test.frugalis.Frugalis");
System.out.println("Loaded class name: " + clazz.getName());
Object instance = clazz.newInstance();
clazz.getMethod("printMyName").invoke(instance);
}
}
Example 4: custom classloader
package test.main;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class MyClassLoader extends ClassLoader {
public MyClassLoader(ClassLoader parent) {
super(parent);
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
System.out.println("Class Loading Started for " + name);
if (name.startsWith("test")) {
return getClass(name);
}
return super.loadClass(name);
}
private Class<?> getClass(String name) throws ClassNotFoundException {
System.out.println("*********Inside getClass*********");
String file = name.replace('.', File.separatorChar) + ".class";
System.out.println("Name of File" + file);
byte[] byteArr = null;
try {
byteArr = loadClassData(file);
System.out.println("Size of byte array "+byteArr.length);
Class<?> c = defineClass(name, byteArr, 0, byteArr.length);
resolveClass(c);
return c;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private byte[] loadClassData(String name) throws IOException {
System.out.println("<<<<<<<<<Inside loadClassData>>>>>>");
InputStream stream = getClass().getClassLoader().getResourceAsStream(
name);
int size = stream.available();
byte buff[] = new byte[size];
DataInputStream in = new DataInputStream(stream);
in.readFully(buff);
in.close();
return buff;
}
}