views:

276

answers:

2

I have a problem while loading my jar file at run time. My hotel.jar is loaded and a method of it (makeReservation) is invoked using the following code:

File file = new File("c:/ComponentFiles/hotel.jar");
URL jarfile = new URL("jar", "", "file:" + file.getAbsolutePath() + "!/");
URLClassLoader cl = URLClassLoader.newInstance(new URL[]{jarfile});
Class  componentClass = cl.loadClass("HotelPackage.HotelMgt");
Object componentObject = componentClass.newInstance();
Method setMethod = componentClass.getDeclaredMethod("makeReservation", null);
setMethod.invoke(componentObject, null);

The problem is in the class HotelPackage.HotelMgt of my jar file , I have a class variable of another class (HotelPackage.Hotel) which is in another jar file. I tried to open and load the other jar file with the same code as above but I receive the exception that cannot find the class def.: Exception in thread "main" java.lang.NoClassDefFoundError: BeanPackage/Hotel

what is the solution?

+1  A: 

You can specify dependencies between JARs by defining the Class-Path property in the JARs' manifest files. Then the JVM will load the dependency JARs automatically as needed.

More information is here: http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html

Nat
A: 

Thanks, but I found another solution that really works. Since I know whole the component series that are going to work with each other, I load them all with one class loader instance (array of URLs). then the classloader itself manages the dependencies.