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 u开发者_StackOverflowsed? 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.
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].)
When you use your first URLClassLoader, the one initialized only with a path for B, then if something in B needs to resolve something in C in order to load, it will come up short. By using the second form you're saying "If you don't find what you need here, look in the 'parent' class loader." This allows C to be resolved and everyone's happy.
(Understand that the only class that can load without referencing other classes is Object -- and even that's a stretch. It's not just that you need to reference the class's superclass -- objects in the base JDK, at least, can be referenced through the system class loader even when there is no parent CL -- but if you call any method of another class or manipulate pointers to another class or any such thing you need to resolve that referenced class.)
精彩评论