Writing Your Own Class loader in JAVA

by Preetha 2012-09-12 11:16:47

Here is an implementation of a custom class loader.

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
public class CustomClassLoader extends ClassLoader {
public CustomClassLoader(){
super(CustomClassLoader.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{
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;
}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;
}

private Hashtable classes = new Hashtable();
}</i>

Here is how to use the CustomClassLoader.

<i>public class CustomClassLoaderTest {

public static void main(String [] args) throws Exception{
CustomClassLoader test = new CustomClassLoader();
test.loadClass(com.test.HelloWorld);
}
}

Tagged in:

843
like
0
dislike
0
mail
flag

You must LOGIN to add comments