The system property java.class.path is used only when the JRE is instantiated. After that I don't think it is re-read. Therefore, changes you make to the property don't really do anything to the existing virtual machine.
You can try using the URLClassLoader as follows:
File fileToAdd = new File("HelloWorld.class") ;
URL u = fileToAdd.toURL() ;
URLClassLoader sysLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
Class sysLoaderClass = URLClassLoader.class;
//use reflection to invoke the private addURL method
Method method = sysLoaderClass.getDeclaredMethod("addURL", new Class[] {URL.class});
method.setAccessible(true);
method.invoke(sysLoader, new Object[] {u});
I want to load a database driver (.jar file) into my swing application.I wrote a ClassLoad to meet this target.But the DriverManager(JDBC) can't get the certain class which is in the jar file I loaded.I think the DriverManager use the system Classloader to load the required class.Could you please tell me how to solve this problem?Thanks
> I want to load a database driver (.jar file) into my
> swing application.I wrote a ClassLoad to meet this
> target.But the DriverManager(JDBC) can't get the
> certain class which is in the jar file I loaded.I
> think the DriverManager use the system Classloader to
> load the required class.Could you please tell me how
> to solve this problem?Thanks
By putting the .jar file in the classpath in the first place. I'd say the vast majority of the time people go off and write some custom class loader, they're barking up the wrong tree and just digging a hole to fall into.
When you create an instance of a class loader whether it is a custom one or not you have to make sure to set the proper parent class loader to the classloader.
Becouse when the classes loaded by new class loader request some other class in the runtime location or the java api thay are loaded from the same class loader so those classes shouyld be reachable by the parent. If not you might even get class not found exceptions even for java.lang.String (It happerned to me once).
Bascally all the classloaders at the runtime must make a tree structure and you have to decide to which branch that your class loader should set in. Normally its the class loader that loaded the class that is creating the class loader or the class loader that loaded the class loader class should be set as the parent of the new class loader.
You will get a better idear about this if you read about the java.lang.ClassLoader in the java doc.
EDIT: Adding another URL to the system class loader is a nice little hack but is it safe to assume that the system class loader is always a URLClassLoader, Is it stated somewhere in the documentation?