ClassLoader - can't find class java.lang.Object
I'm playing a little bit with ClassLoader. I write my own class loader and use it to load HelloWorld class. While loading HelloWorld class, the class loader can't find java.lang.object so it gives the exception as following:
Quote:
Exception in thread "main" java.lang.NoClassDefFoundError: java/lang/Object
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader. java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java :616)
at CustomClassLoader.findClass(CustomClassLoader.java :28)
at CustomClassLoader.loadClass(CustomClassLoader.java :15)
at CustomClassLoaderTest.main(CustomClassLoaderTest.j ava:5)
I've checked the file rt.jar and it includes java/lang/Object.class already. Do you know how to fix this problem? Thank you so much.
Here is my class loader:
Code:
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{
String classPath = (String)ClassLoader.getSystemResource(className.replace('.',File.separatorChar)+".class").getFile();
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();
}
And the way I use it:
Code:
public class CustomClassLoaderTest {
public static void main(String [] args) throws Exception{
CustomClassLoader test = new CustomClassLoader();
Class cHelloWorld = test.loadClass("com.octech.test.HelloWorld");
}
}