Search code examples
javaclassloader

ClassLoader loadClass throws ClassNotFoundException


String pathToJar = "C:\\Users\\dtn\\jb_workspace\\helloworld-mdb\\target\\jboss-as-helloworld-mdb.war";

URL[] urls = { new URL("jar:file:///" + pathToJar+"!/") };
URLClassLoader urlcl = new URLClassLoader(urls);
urlcl.loadClass("org.jboss.as.quickstarts.mdb.HelloWorldTopicMDB");

The exception I got is:

Exception in thread "main" java.lang.ClassNotFoundException: org.jboss.as.quickstarts.mdb.HelloWorldTopicMDB

When I investigated into the problem, I saw the HelloWorldTopicMDB.class file is stored inside WEB-INF/classes.

Can that somehow the root of the problem ? Since I tried with other jar file, with package name at the root of the jar directory structure, there is no error.

Thanks very much for any reply.


Solution

  • In a proper war file, compiled classes are always in WEB-INF/classes, and jars needed at runtime are in WEB-INF/lib.

    That is definitely the cause of your problem. This resource should help you load classes from within the war file.

    I must say though this seems rather unorthodox. Usually web servers load classes from war files. Can I ask why you are doing this?

    Anyway, hope this helps.