Search code examples
javaurlclassloader

URLClassLoader throws No Class Definition found exception


I have 3 Java projects A, B and C. B is like an add-on to A. A and B both depend on project C for some classes.

Now in project A when I use a URLClassLoader as follows:

URLClassLoader ucl = new URLClassLoader(urls); //urls are paths to some classes in B

Now when using these ucl, when I call some methods in B, it gives me No Class Definition found exception. This is for a class which is C.

Now when I use the ClassLoader as follows:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader ucl = new URLClassLoader(urls, classLoader);

This works fine when I call the methods in B. My Question:

1) When I do it the first way, which ClassLoader is being used? I read the JavaDocs, but couldn't find anything that I could explain myself to.
2) Is there a way to get a ClassLoader which will be specific to project B, that I can use somehow, so that I won't hit any dependency issues?

Thanks for any help.


Solution

  • The default class loader is the system class loader (loads the classes on the classpath).

    If you loaded classes in B with a specific class loader, use that instance. Otherwise someTypeInB.getClass().getClassLoader() will do as a hack.

    (Note: Using URLClassLoader.newInstance is generally preferable to new URLClassLoader, as it adds in security measures necessary (though not really sufficient) for use with untrusted code. Also using the thread context class loader is generally a bad idea - you introduce a dependency upon the local piece of code to however threads are setup and used [which probably doesn't have any coherent policy applied to it anyway].)