Hi,
I'm trying to dynamically add a jar to the classpath at runtime by using a URLClassLoader. The first time I try to load a class my class loader I get a ClassNotFoundException.
Here's my code:
I added some logging to find out what URLs were referenced by the class loader and it's parent class loader, and tried running a few different
test cases. If I run my app as intended, I get the following:
java -cp launcher.jar com.bbt.planner.util.PlClientGo
1 URL in custom loader: file:/C:/dev/bbt/test/planner/version/planner.jar
1 URL in parent loader: file:/C:/dev/bbt/test/planner/launcher.jar
Exception in
thread "main" java.lang.NoClassDefFoundError: com/bbt/planner/util/
MyClass
at com.bbt.planner.util.PlClientGo.main(PlClientGo.java:45)
Caused by: java.lang.ClassNotFoundException: com.bbt.planner.util.MyClass
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 1 more
If, however, I run explicitly pathing in my jar in the class path the code works and I get:
java -cp launcher.jar;version/planner.jar com.bbt.planner.util.PlClientGo -verbose
1 URL in custom loader: file:/C:/dev/bbt/test/planner/version/planner.jar
1 URL in parent loader: file:/C:/dev/bbt/test/planner/launcher.jar
2 URL in parent loader: file:/C:/dev/bbt/test/planner/version/planner.jar
What's interesting about that is that the URL held in the class loader I instantiated myself is exactly the same as the one in the parent class loader that was generated by the '-cp' when I ran the second test case. I.e. my jar is in the correct place with the correct class in it, but for some reason my URLClassLoader isn't able to load the class if it isn't found by parent delegation.
Any ideas about what could be wrong or where to look / what to try next would be greatly appreciated.