加载依赖于另一个 jar 文件的 jar 文件时出现问题
我在运行时加载 jar 文件时遇到问题。 我的 hotel.jar 已加载,并使用以下代码调用它的方法(makeReservation):
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);
问题出在我的 jar 文件的类 HotelPackage.HotelMgt 中,我有另一个类(HotelPackage.Hotel)的类变量,它是在另一个 jar 文件中。 我尝试使用与上面相同的代码打开并加载另一个 jar 文件,但收到找不到类定义的异常: 线程“main”java.lang.NoClassDefFoundError:BeanPackage/Hotel中出现异常
解决方案是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过在 JAR 的清单文件中定义 Class-Path 属性来指定 JAR 之间的依赖关系。 然后 JVM 将根据需要自动加载依赖 JAR。
更多信息如下: http://java.sun.com /docs/books/tutorial/deployment/jar/downman.html
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
谢谢,但我找到了另一个真正有效的解决方案。 因为我知道将要相互协作的整个组件系列,所以我使用一个类加载器实例(URL 数组)加载它们。 然后类加载器本身管理依赖关系。
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.