Search code examples
javaclassloader

Class loading issue


I successfully loaded a class at runtime, and called newInstance() on that class, and created an object from it.

But, later on in the program, I am trying to find that class again by name. And for some reason, the program can't find it.

Here's the code:

MyClassLoader mcl = new MyClassLoader();
Class<?> c = mcl.loadClass("models." + getModelClassName(), getByteCode());

here is the loadClass method in MyClassLoader:

   public Class<?> loadClass(String className, byte[] classData){
           return this.defineClass(className,classData,0,classData.length);
        }

Anyway, it appears I have successfully loaded the class, because I can call newInstance on the newly loaded class "c":

     Object o = c.newInstance();

(So, no problems, yet).

However, later on in the program, I make the following call:

Class<? extends DB4oModel> dbClass = null;

try{

   dbClass = (Class<? extends DB4oModel>) Class.forName("models."+className);

} catch(ClassNotFoundException e1){

      // this exception is thrown by my program !!

}

My only guess as to what the problem could be is that the class has been successfully loaded for one classloader but the other classloader doesn't know about the class? I really have no idea. Please help, thanks.


Solution

  • You need to specify the classloader (which has loaded your model class) as a parameter in Class.forName();

    See this!