我有一个文件夹libs
其中包含多个 JAR,并且我有一个应用程序(假设 MyTest.jar
)使用这些库中的一些类。我需要的是运行 MyTest.jar
与一种-cp
( -classpath
) 参数将添加文件夹 libs
中的所有 JAR完全到类路径。
我已经尝试过java -cp E:\libs -jar MyTest.jar
。然而,这似乎根本没有加载库,正如我得到的这个错误所示(它指出它找不到库类之一 me.darksidecode.simpleconfigs.Config
):
Exception in thread "main" java.lang.NoClassDefFoundError: me/darksidecode/simpleconfigs/Config
at me.darksidecode.KekGUI.<init>(KekGUI.java:31)
at me.darksidecode.KekGUI.main(KekGUI.java:63)
Caused by: java.lang.ClassNotFoundException: me.darksidecode.simpleconfigs.Config
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)
... 2 more
抛出异常的行是:
Config testcfg = new Config("hello = world");
哪里Config
( me.darksidecode.simpleconfigs.Config
) 是 SimpleConfigs.jar
的一个类库,存在在我的 libs
中( E:\libs
) 文件夹并且有效。
我也尝试显式指定库之一( SimpleConfigs.jar
),但无济于事: java -cp E:\libs\SimpleConfigs.jar -jar MyTest.jar
。发生同样的错误。
我怎样才能让它发挥作用?
编辑:看来我必须在 MyTest.jar
中指定类路径的 MANIFEST.MF 文件。这里我遇到了一个新问题:我只能在 Class-Path
中指定确切的 JAR 名称。 ,像这样:
Class-Path: /E:/libs/SimpleConfigs.jar
就是这样工作的。但是当我尝试指定整个目录时:
Class-Path: /E:/libs/
它再次开始抛出上述错误 ( java.lang.NoClassDefFoundError
)。
最佳答案
java 文档指出
-jar
Executes a program encapsulated in a JAR file. The first argument is the name of a JAR file instead of a startup class name. For this option to work, the manifest of the JAR file must contain a line in the form Main-Class: classname. Here, classname identifies the class with the public static void main(String[] args) method that serves as your application's starting point.
When you use this option, the JAR file is the source of all user classes, and other user class path settings are ignored`.
一种解决方法是将 MyTest.jar 附加到类路径 (-cp) 并指定 MyTest.jar 中的主类作为 java 的参数
java -cp Mytest.jar;E:\libs\* me.darksidecode.KekGUI
关于java - 将所有 JAR 中的所有类加载到类路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50114744/